How to use volatile in kotlin

Words
114
Reading
1 min
Listen
Play
8y

What is volatile

volatile is a keyword in java. volatile in Java is used as an indicator to Java compiler and Thread that do not cache value of this variable and always read it from main memory. The Java volatile keyword can not be used with method or class and it can only be used with a variable.

Volatile in kotlin

volatile in Kotlin is replaced by @Volatile.

@Target([AnnotationTarget.FIELD]) annotation actual class 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.

Example in kotlin

public class LazySingleton {  
    private static volatile LazySingleton instance = null;
    public static LazySingleton getInstance() {
        if (instance == null) {
            instance = new LazySingleton();
        }
        return instance;
    }
}

When to use

  • If a variable is not shared between multiple threads, you don't need to use volatile keyword with that variable.
How to use volatile in kotlin | Ecency