# Java/Kotlin : @Volatile

> If get to know something new by reading my articles, don't forget to endorse me on [LinkedIn](https://www.linkedin.com/in/rommansabbir/)

# What is `@Volatile`?

`Volatile` keyword is used to modify the value of a variable by different threads. It is also used to make classes thread safe. It means that multiple threads can use a method and instance of the classes at the same time without any problem. The *volatile* keyword can be used either with primitive type or objects. The *volatile* keyword does not cache the value of the variable and always read the variable from the main memory.

# When to Use?

* You can use a *volatile* variable if you want to read and write long and double variable automatically.
    
* It can be used as an alternative way of achieving synchronization in *Java/Kotlin*.
    
* All reader threads will see the updated value of the volatile variable after completing the write operation. If you are not using the *volatile* keyword, different reader thread may see different values.
    
* It is used to inform the compiler that multiple threads will access a particular statement. It prevents the compiler from doing any reordering or any optimization.
    
* If you do not use *volatile* variable compiler can reorder the code, free to write in cache value of volatile variable instead of reading from the main memory.
    

![carbon(3).png](https://cdn.hashnode.com/res/hashnode/image/upload/v1646638924627/KRr7v9ZyZ.png align="left")

Kotlin Example:

```plaintext
object MultithreadedDataHolder {
    @Volatile
    var someData: Any? = null
        private set

    fun updateData(data: Any) {
        this.someData = data
        println("Data stored...")
    }
}
```

# Implementation in Kotlin

%[https://gist.github.com/rommansabbir/94e899f5d2c66dfb9f8346fc673db97b]
