Sobes.tech
Junior — Middle

How can you ensure safe updating of a variable that is accessed by multiple threads simultaneously?

sobes.tech AI

Answer from AI

There are several approaches to safely update a variable that is accessed concurrently by multiple threads:

  1. Synchronization (synchronized) — locking a critical section of code so that only one thread can modify the variable at a time.

  2. Classes from the java.util.concurrent.atomic package — for example, AtomicInteger, AtomicReference, etc., which provide atomic operations without explicit synchronization.

  3. Using volatile — guarantees visibility of changes to the variable between threads, but does not ensure atomicity of complex operations.

  4. Lock (java.util.concurrent.locks.Lock) — a more flexible locking mechanism.

Example with AtomicInteger:

import java.util.concurrent.atomic.AtomicInteger;

public class Counter {
    private AtomicInteger count = new AtomicInteger(0);

    public void increment() {
        count.incrementAndGet(); // atomic increment
    }

    public int getCount() {
        return count.get();
    }
}

This approach allows safe updating of the value without the risk of race conditions.