Sobes.tech
Senior

What do we get and what do we sacrifice when using volatile?

sobes.tech AI

Answer from AI

In Java, the keyword volatile guarantees that changes to a variable will be visible to all threads immediately, meaning that reading and writing the variable will not be cached locally in threads. This ensures visibility of changes and prevents some issues related to caching and instruction reordering.

What we get:

  • Guaranteed visibility of variable changes between threads.
  • Prohibition of reordering read/write operations with this variable.

What we sacrifice:

  • Performance, as access to volatile variables can be slower due to the need for synchronization with main memory.
  • volatile does not provide atomicity for complex operations (e.g., increment), so additional synchronization is needed for such cases.

Example:

volatile boolean flag = false;

// Thread 1
flag = true;

// Thread 2
if (flag) {
    // will definitely see the update to flag
}
What do we get and what do we sacrifice when using… - sobes.tech