Skip to content
Veltoryx Technologies
ProLesson 9.3Intermediate3 min readUpdated 30 October 2026

Race conditions and synchronized

See a race condition lose updates in front of you, understand why count++ isn't safe, and fix it with synchronized.

This lesson shows the most important concurrency bug, the race condition, and Java's oldest fix for it, synchronized.

01A race condition you can see

Two threads each add 100,000 to a shared counter. The answer should be 200,000:

Race.java
public class Race {
    static int count = 0;

    public static void main(String[] args) throws InterruptedException {
        Runnable addMany = () -> {
            for (int i = 0; i < 100_000; i++) {
                count++;                       // NOT atomic
            }
        };
        Thread a = new Thread(addMany);
        Thread b = new Thread(addMany);
        a.start(); b.start();
        a.join(); b.join();
        System.out.println("Count: " + count + " (expected 200000)");
    }
}
Expected output
Count: 137518 (expected 200000)

The number is usually lower than 200,000, and different every run.

Loading the rest of the lesson…