How to use volatile in kotlin

in #volatile6 years ago

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.
Sort:  

Congratulations @sharpchain! You received a personal award!

Happy Birthday! - You are on the Steem blockchain for 1 year!

You can view your badges on your Steem Board and compare to others on the Steem Ranking

Vote for @Steemitboard as a witness to get one more award and increased upvotes!

Coin Marketplace

STEEM 0.30
TRX 0.12
JST 0.032
BTC 61227.60
ETH 3022.96
USDT 1.00
SBD 3.88