Sobes.tech
Middle+

In which cases should you use atomic, and in which synchronized?

sobes.tech AI

Answer from AI

synchronized is used to protect a block of code or a method from being accessed concurrently by multiple threads, ensuring exclusive access.

atomic classes (e.g., AtomicInteger, AtomicReference) provide atomic operations on primitive types and references, which do not require explicit locking. They are based on the Compare-And-Swap (CAS) mechanism and are suitable for scenarios where an atomic operation on a single value is needed without full locking.

Use atomic for:

  • Atomic operations on individual variables (increment, decrement, update).
  • Counters and flags accessed from multiple threads.
  • Scenarios where performance is critical and locking overhead can be avoided.

Use synchronized for:

  • Protecting complex data structures and objects from concurrent modification.
  • Coordinating access to multiple related variables.
  • Locking entire blocks of code or methods.

Example of synchronized:

class Counter {
    private int count = 0;

    public synchronized void increment() {
        count++;
    }

    public synchronized int getCount() {
        return count;
    }
}

Example of AtomicInteger:

import java.util.concurrent.atomic.AtomicInteger;

class AtomicCounter {
    private final AtomicInteger count = new AtomicInteger(0);

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

    public int getCount() {
        return count.get(); // Atomic get
    }
}
In which cases should you use atomic, and in which… - sobes.tech