Java concurrency exercises
Java provides rich concurrency utilities in java.util.concurrent, but multithreaded programming is fraught with race conditions: non-atomic compound operations (like count++), caching of variables without volatile, and synchronized deadlock cycles.
Identify concurrency hazards and implement thread-safe fixes.
The concurrency bugs you will meet
- count++ is not atomic: it requires read, modify, and write; use AtomicInteger or synchronized.
- Without volatile or synchronization, thread memory caches may not see updates made by other threads.
- Iterating over a standard HashMap or ArrayList from multiple threads causes data corruption or infinite loops.
- Calling Thread.sleep() or blocking operations while holding a monitor lock blocks all competing threads.
The exercises
Medium
Errors you might be searching for
More JavaScript practice by topic
Questions
What does volatile do in Java?
The volatile keyword guarantees memory visibility across threads, preventing CPU registers and caches from caching outdated variable values.