Volatile variables
Allow me to start by clarifying that volatile variables will not solve problems like the thread-safe counter that we are trying to implement. Nevertheless, volatile variables can be used in some scenarios as a simple solution when we need information to be shared among threads.
Thread cache
On the JVM, each thread may contain a cached copy of any non-volatile variable. This cache is not expected to be in sync with the actual value of the variable at all times. So changing a shared state in a thread will not be visible in other threads until the cache is updated.
@Volatile
In order to force changes in a variable to be immediately visible to other threads, we can use the annotation @Volatile
, a in the following example:
@Volatile var shutdownRequested = false
This will guarantee visibility of changes for other threads as soon as the value is changed. This means that if thread X modifies the value of shutdownRequested
, thread Y will be able to see the change immediately.