The Java Volatile Keyword Flashcards
What is the Java Volatile Keyword used for?
It is used to guarantee visibility of changes to variables across threads
What does it mean to declare a variable as Volatile to the JVM?
By declaring the a variable volatile, all writes to the variable will be written back to main memory immediately.
Also, all reads of the variable will be read directly from main memory.
What does it mean to declare a variable as Synchronised to the JVM?
Synchronised basically adds a critical flag to a specific variable. Thus, the JVM will know to block all but one write request to the variable at a time. It will, however, allow infinitely many simultaneous read requests - as long as no write request is currently occurring.
When should you use Volatile
Use Volatile when your variables are going to get read by multiple threads, but written to by only one thread.
When should you use Synchronised?
Use Synchronised when your variables will get read and written to by multiple
threads