Understanding and Avoiding Common Concurrency Bugs in Java
This article introduces the four major categories of multithreaded bugs—data races, atomicity failures, ordering failures, and deadlocks—explains their causes with Java examples, and provides practical techniques such as using state machines, volatile variables, consistent lock ordering, and proper exception handling to prevent them.
Testing engineers often struggle with concurrent logic, encountering bugs like data races and deadlocks that are hard to detect or reproduce. This article, originally published on Qtest, records common multithreaded bugs and offers guidance for developers.
Classification of concurrency bugs
Data race : occurs when two threads access the same shared memory, at least one write, without synchronization, leading to crashes such as null‑pointer exceptions.
Atomicity failure : when multiple memory accesses that should appear indivisible are interleaved by other threads, causing lost updates; the article shows a Java example where two threads increment a shared array element incorrectly.
Ordering failure : arises when the assumed execution order of memory operations is broken by nondeterministic thread scheduling, potentially skipping intended loops.
Deadlock : happens when threads wait for each other's resources, illustrated by a symmetric deadlock example involving two objects locking each other.
Beyond these four, rarer bugs such as starvation, livelock, lock convoy, and priority inversion are mentioned with reference links.
Mitigation techniques
• Avoid global static flags; use a state‑machine pattern (e.g., Android's com.android.internal.util.StateMachine ).
• Ensure memory visibility with volatile variables.
• Maintain a consistent lock acquisition order across threads.
• Write precise try‑catch blocks that handle specific exceptions and expose concurrency issues early in testing.
• Give meaningful names to created threads to simplify debugging.
The article concludes with additional resources and references on concurrency defect detection and avoidance.
360 Tech Engineering
Official tech channel of 360, building the most professional technology aggregation platform for the brand.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.