Common Concurrency Issues and Solutions in Java
Common Concurrency Issues
JVM enables multi-threads in Java application. There are common problem for Multi-Threads such as Race Condition, Deadlocks, Starvation.
Race Conditions
Example: different threads try to read and write value to same variable. The value depends on which thread writes the value to the variable.
Deadlocks
Example: One thread locks the resource and another thread keeps waiting on it.
Starvation
Example: One greedy thread constantly acquiring the resource resulting anther thread being starvation or no progress.
Java Solutions
Java provides several solutions to handle concurrency issues such as Thread-safe objects, Thread-safe collection, Synchronisation, Atomic Variables, volatile and other High-Level Concurrency API.
Thread-safe objects
Examples: Immutable Objects
Thread-safe Collections
Examples: CopyOnWriteArrayList, ConcurrentHashMap
Synchronisation
Examples: synchronized
key word
Atomic Variables
Examples: AtomicInteger
, AtomicLong
, AtomicReference
These variables provide atomic operation which complete operation in a single step and compare-and-swap (CAS) to ensure data integrity.