Category: java
What Is a Race Condition?
Published on 27 Oct 2026
Explanation
A race condition occurs when the result depends on the timing or interleaving of concurrent operations. It commonly happens when threads access shared mutable state without proper coordination.
Code:
class UnsafeCounter {
int count;
void increment() { count++; }
}
public class RaceDemo {
public static void main(String[] args) throws InterruptedException {
UnsafeCounter c = new UnsafeCounter();
Runnable task = () -> { for (int i = 0; i < 10000; i++) c.increment(); };
Thread a = new Thread(task), b = new Thread(task);
a.start(); b.start(); a.join(); b.join();
System.out.println(c.count); // May be less than 20000
}
}
Explanation
The expression count++ involves reading the current value, adding one, and writing the result. Two threads can read the same value and overwrite each other's increments.
Code:
class Counter {
private int count;
public void increment() {
int current = count;
count = current + 1;
}
public int getCount() { return count; }
}
Explanation
Use synchronized to ensure only one thread at a time performs a critical update on the same object. All relevant accesses must follow the same synchronization strategy.
Code:
class SynchronizedCounter {
private int count;
public synchronized void increment() { count++; }
public synchronized int getCount() { return count; }
}
Explanation
AtomicInteger supports atomic updates such as incrementAndGet(). It is useful for simple counters and flags, while more complex multi-step invariants may still require synchronization or locks.
Code:
import java.util.concurrent.atomic.AtomicInteger;
public class AtomicCounterDemo {
public static void main(String[] args) throws InterruptedException {
AtomicInteger count = new AtomicInteger();
Runnable task = () -> { for (int i = 0; i < 1000; i++) count.incrementAndGet(); };
Thread a = new Thread(task), b = new Thread(task);
a.start(); b.start(); a.join(); b.join();
System.out.println(count.get());
}
}
Explanation
Race conditions can affect inventory, ticket booking, and bank balances. Java locks protect data only within the relevant JVM; distributed applications may also need database transactions, conditional updates, or distributed coordination.
Code:
class InventoryService {
private int stock = 1;
public synchronized boolean purchase() {
if (stock <= 0) return false;
stock--;
return true;
}
}