Volatile

Description

For example, if we have 2 thread, running the same piece of code.

Thread 1: Control the variable flag

boolean flag = true

flag = false

Thread 2: Monitor the flag variable to process some code

boolean flag = true

while (flag) {
	// processing
}

Given this code running as this, it wouldn't work because both thread 1 and thread 2 all have its own local cache containing its own value of flag:

Pasted image 20230810100749.png

To tell Java flush this cache, we declare as volatile

So:

volatile boolean flag = true

Doing this will make thread 2 cache update the newest state of flag

[!Note]
In reality, without volatile might or might not work depends on if the JVM decided to cache it. However to be sure, we always explicitly declare volatile

Gotcha

For example the same part of code, if we have

volatile int value = 1

And we have

Thread 1:

value++

Thread 2:

value++

This will not work because volatile solves visibility problem not concurrency problem

  • Visibility problem happens when 1 thread cannot see the value of another thread.

In this case, the flow for Thread 1 and Thread 2 happens as below:

Pasted image 20230810101619.png

As a result, it's not guarantee that Thread 2 has the latest value of Thread 1.

To solve this, we use Synchronisation or we can use some threadsafe class like AtomicInteger

Pasted image 20230810102043.png