Sobes.tech
Junior — Middle

How does the use of the synchronized keyword differ from atomic operations in ensuring thread safety in Java?

sobes.tech AI

Answer from AI

The synchronized keyword in Java is used to lock a critical section of code, ensuring exclusive access to a resource for one thread. It guarantees that only one thread can execute a synchronized block or method at a time, and also provides visibility of variable changes between threads.

Atomic operations (e.g., classes from java.util.concurrent.atomic, such as AtomicInteger) ensure that individual operations (like increment, compare, and set) are performed as indivisible, without using locks. They are usually faster because they do not involve locking, but are limited in functionality — suitable for simple operations on individual variables.

In summary:

  • synchronized — locks a code block, suitable for complex operations, and guarantees mutual exclusion and visibility.
  • Atomic operations — ensure indivisibility of individual operations without locks, effective for simple cases.

Example of an atomic operation:

import java.util.concurrent.atomic.AtomicInteger;

AtomicInteger counter = new AtomicInteger(0);
counter.incrementAndGet(); // atomic increment

Example of synchronized:

private int counter = 0;

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