Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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.
/**
* We have a data holder class called [MultithreadedDataHolder] that hold some data
* which will be used by different clients from different [Thread]s. Multiple clients
* can access the same object simultaneously.
*
* Any object that is annotated with Annotation [Volatile] make sure that the changes
* made in one thread are immediately reflect in other thread.
*/
object MultithreadedDataHolder {
/*It's guaranteed that all reader threads will see the updated value of the
volatile variable once the write operation is completed, without volatile
keyword different reader thread may see different values.*/
@Volatile
var someData: Any? = null
private set
fun updateData(data: Any) {
this.someData = data
println("Data stored...")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment