Video in progress
What is a race condition? Show it with a simple example.
When the result depends on the order in which threads run, that is a race condition. The classic example is two threads running the same count++, and some increments get lost.
📖 Answer
class Counter {
int count = 0;
void inc() { count++; }
}
Counter c = new Counter();
Runnable r = () -> { for (int i = 0; i < 100_000; i++) c.inc(); };
Thread a = new Thread(r), b = new Thread(r);
a.start(); b.start();
a.join(); b.join();
System.out.println(c.count); // not 200000, for example 137452
count++ looks like one operation, but it is really three: read, add one, write. If both threads read 5 at the same time, both write 6, and one increment is lost.
Another common form is "check, then act":
if (!map.containsKey(key)) { // both threads see false
map.put(key, load(key)); // both of them write
}
Ways to fix it: synchronized, AtomicInteger, or atomic methods like ConcurrentHashMap.computeIfAbsent. The best fix is to reduce shared mutable state in the first place.
Sign up to mark studied questions and save your progress.