Course contentsShow
← Java
Lesson 2643 of 2,87049. Synchronization and LockingFree lesson

A Simple Counter Example

Demonstrate a shared counter incremented by multiple threads, showing how final values can be incorrect.

A Simple Counter Example

What You'll Learn

You'll see a concrete demonstration of how multiple threads incrementing a shared counter can produce incorrect final values due to race conditions.

The Classic Counter Problem

Imagine two cashiers sharing a single paper tally sheet to count customers. Both read the number, add one, and write it back. If they do this simultaneously, updates can be lost—one cashier might overwrite the other's count without seeing their update first.

This is exactly what happens with threads and shared variables.

The Demonstration

class Counter {
    private int count = 0;

    public void increment() {
        count++;  // Not atomic!
    }

    public int getCount() {
        return count;
    }
}

public class CounterDemo {
    public static void main(String[] args) throws InterruptedException {
        Counter counter = new Counter();

        Runnable task = () -> {
            for (int i = 0; i < 1000; i++) {
                counter.increment();
            }
        };

        Thread t1 = new Thread(task);
        Thread t2 = new Thread(task);

        t1.start();
        t2.start();

        t1.join();
        t2.join();

        System.out.println("Final count: " + counter.getCount());
        System.out.println("Expected: 2000");
    }
}

Why It Fails

The count++ operation looks simple but actually involves three steps:

  1. Read the current value
  2. Increment it in memory
  3. Write it back

When two threads execute these steps simultaneously, their read-increment-write sequences can interleave, causing lost updates. You might see 1850, 1923, or any value less than the expected 2000.

Key Takeaway:
A simple counter shared between threads demonstrates race conditions in action—count++ is not atomic, so multiple threads can lose updates, producing incorrect final values despite all operations completing.