Java Protect a Shared Update as One Operation
A read-modify-write sequence is not made atomic just because it fits on one line. Several threads can read the same old value and overwrite one another’s updates.
Understand the idea
synchronized protects a critical section using a monitor and supplies visibility guarantees associated with that locking discipline. Every participating access must follow the same policy. volatile provides visibility and ordering rules for the field but does not make count++ an atomic compound action. AtomicInteger offers operations such as incrementAndGet for a single shared integer; a multi-field invariant still needs a wider design.
Run it locally
Use a local JDK 21 or newer. Save the complete example as Main.java in a separate lab folder, then compile and run it with the commands below. Java examples do not run in Bhylu’s browser playground. The -ea option enables assertion checks used by some lessons.
javac --release 21 -encoding UTF-8 -d out Main.java
java -ea -cp out MainA worked example
import java.util.concurrent.atomic.AtomicInteger;
public class Main {
public static void main(String[] args) throws InterruptedException {
AtomicInteger count = new AtomicInteger();
Thread first = new Thread(() -> { for (int i = 0; i < 1000; i++) count.incrementAndGet(); });
Thread second = new Thread(() -> { for (int i = 0; i < 1000; i++) count.incrementAndGet(); });
first.start(); second.start();
first.join(); second.join();
System.out.println(count.get());
}
}
Expected output
2000Each increment is an atomic update, so the two thousand increments are retained. The joins ensure both workers finish before the result is printed. Atomicity here covers one numeric operation; it would not automatically keep a separate booked count and remaining count consistent as one reservation transaction.
Check the official Java documentation for detailed contracts and supported options.