Skip to content

Instantly share code, notes, and snippets.

@rommansabbir
Created March 7, 2022 07:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rommansabbir/94e899f5d2c66dfb9f8346fc673db97b to your computer and use it in GitHub Desktop.
Save rommansabbir/94e899f5d2c66dfb9f8346fc673db97b to your computer and use it in GitHub Desktop.
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