Sobes.tech
Junior — Middle

When and why should the combination of the keywords synchronized and volatile be used in Java to ensure thread safety?

sobes.tech AI

Answer from AI

The volatile keyword in Java guarantees that reading and writing a variable will occur directly from main memory, not from the thread's cache, ensuring visibility of changes between threads.

The synchronized keyword provides mutual exclusion, meaning only one thread can execute a synchronized block at a time, and also guarantees full memory synchronization when entering and exiting the block.

The combination of volatile and synchronized is used when it is necessary to ensure both visibility of variable changes between threads and atomicity of operations on it. For example, if a variable is read frequently without locks but sometimes updated within a synchronized block, volatile guarantees that threads see the current value, and synchronized ensures that the update is atomic.

Example:

private volatile int counter;

public void increment() {
    synchronized(this) {
        counter++;
    }
}

public int getCounter() {
    return counter; // sees the current value thanks to volatile
}

Thus, volatile provides visibility, and synchronized provides atomicity and mutual exclusion.

When and why should the combination of the keywords… - sobes.tech