A Nice Race Condition

Rishabh Agarwal
6 min readFeb 13, 2024
Photo by Jonathan Chng on Unsplash

Race conditions are the bitter truth of concurrent applications. But why would anyone call a race condition nice? The fascination of this race condition lies in its subtlety on the outside, countered by the intricate complexities under the hood. It is probably the reason why people call it a Nice Race Condition.

Despite the disagreement on the naming, this race-condition serves as an amazing case study of how seemingly innocent programs can fail in concurrent settings.

In this blog, we will dissect this race-condition. We will understand how and why this race condition occurs and what are some ways to eliminate this race-condition in our applications.

Let us Start…

Consider the following Java code,

public class NiceRC {

public static void main(String[] args) {
final Map<Object, Object> unsafeMap = new HashMap<>();
final List<Thread> threads = new ArrayList<>();
for (int i = 0; i < 5; ++i) {
threads.add(new Thread(() -> {
for (int j = 0; j < 100000; ++j) {
unsafeMap.put(new Object(), new Object());
}
}));
}
threads.forEach(Thread::start);
threads.forEach(thread -> {
try {
thread.join();
} catch (InterruptedException e) {…

--

--

Rishabh Agarwal

Software Developer 2 @ Schrödinger | IIT CSE Graduate - Writes about Software Engineering!