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.
Congratulations @sharpchain! You received a personal award!
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!
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit