Java: mutual exclusion with synchronized

A race condition happens when threads read and write shared data without coordination. The statement counter++ is really three steps: read, add one, write. If two threads interleave those steps, one update can overwrite the other and increments are lost.

Java
class Main {
  private static int counter = 0;
  private static final Object lock = new Object();

  static void work() {
    for (int i = 0; i < 100000; i++) {
      synchronized (lock) {
        counter++;
      }
    }
  }

  public static void main(String[] args) throws InterruptedException {
    Thread a = new Thread(Main::work);
    Thread b = new Thread(Main::work);
    a.start();
    b.start();
    a.join();
    b.join();
    System.out.println("counter=" + counter);
  }
}
Read the full lesson