Romman Sabbir
Romman's Blog

Romman's Blog

Java/Kotlin : @Volatile

Java/Kotlin : @Volatile

Marks the JVM backing field of the annotated property as volatile, meaning that writes to this field are immediately made visible to other threads.

Romman Sabbir's photo
Romman Sabbir
·Mar 7, 2022·

2 min read

Table of contents

  • What is @Volatile?
  • When to Use?
  • Implementation in Kotlin

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

Kotlin Example:

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

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

Implementation in Kotlin

 
Share this