Mastering Java Concurrency: Threads, Locks, ThreadPools, and More
This comprehensive guide explores Java concurrency fundamentals—including processes, threads, daemon threads, thread states, synchronization methods, scheduling algorithms, wait vs. sleep, ThreadLocal, locks, volatile, CAS, Unsafe, thread pools, executor policies, blocking queues, Fork/Join, atomic classes, barriers, semaphores, deadlock, IPC, and interruption—providing essential knowledge for building high‑performance backend systems.
This article provides a comprehensive overview of Java concurrency concepts, covering processes, threads, daemon threads, thread states, synchronization methods, scheduling algorithms, differences between wait and sleep, ThreadLocal, synchronized vs ReentrantLock, volatile, CAS, Unsafe, thread pools, executor policies, blocking queues, conditions, Fork/Join framework, atomic classes, barriers, semaphores, deadlock, inter‑process communication, and thread interruption.
1. Threads and Processes
Process is an entity with its own address space, typically containing text, data, and stack regions.
Thread consists of thread ID, program counter, registers, and a stack; it shares the process’s resources.
Key differences: address space, resource ownership, scheduling unit, and concurrency capability.
2. Daemon Threads
Java defines two thread types: User Thread and Daemon Thread. Daemon threads depend on the thread that created them; when the main thread finishes, daemon threads terminate automatically (e.g., garbage‑collector thread).
3. Java Thread States
NEW – thread created but not started.
RUNNABLE – thread executing or ready for CPU time slice.
BLOCKED – waiting to acquire a monitor lock.
WAITING – waiting after calling wait() or join() without timeout.
TIMED_WAITING – waiting with a timeout (e.g., wait(long), sleep(long)).
TERMINATED – run() method completed.
4. Synchronization and Scheduling Methods
wait(): puts thread into waiting state and releases the object lock.
sleep(): puts thread to sleep without releasing the lock.
notify(): wakes one waiting thread (selection is JVM‑determined).
notifyAll(): wakes all waiting threads.
5. Process Scheduling Algorithms
Real‑time systems: FIFO, SJF, SRTF.
Interactive systems: RR, HPF, multilevel queue, shortest‑process‑first, guaranteed scheduling, lottery scheduling, fair‑share scheduling.
6. Difference Between wait() and sleep()
wait() is defined in Object, sleep() in Thread.
wait() releases the monitor lock; sleep() does not.
sleep() does not yield CPU resources; wait() allows other threads to run.
sleep(milliseconds) requires a timeout; wait() may wait indefinitely until notified.
7. ThreadLocal and Deadlock Analysis
ThreadLocal provides a separate variable instance for each thread, enabling data isolation without contention.
8. synchronized vs ReentrantLock
synchronized is simple and readable, suitable for low contention scenarios. ReentrantLock offers richer features (tryLock, timed lock, interruptible lock) and performs better under high contention.
9. volatile vs synchronized
volatile works at variable level; synchronized locks objects or classes.
volatile does not block threads; synchronized does.
synchronized guarantees atomicity, visibility, and ordering; volatile only guarantees visibility.
volatile prevents compiler optimizations; synchronized allows them.
To make a volatile variable safely thread‑visible, writes must not depend on the current value and the variable must not be part of a larger invariant.
10. CAS (Compare‑And‑Set)
CAS is an optimistic lock technique that atomically updates a variable only if its current value matches the expected value.
11. Unsafe Class Details
Provides low‑level memory allocation (allocateMemory, reallocateMemory, freeMemory).
Can access and modify object fields, even private ones.
Supports thread parking/unparking via park/unpark.
Implements CAS operations.
12. Thread Pools
Thread pools create a set of worker threads at startup to handle tasks, reducing thread creation overhead and improving response time.
13. ThreadPoolExecutor Parameters
corePoolSize – number of core threads that stay alive.
maximumPoolSize – maximum number of threads.
keepAliveTime – idle time before non‑core threads are terminated.
unit – time unit for keepAliveTime.
workQueue – task queue (SynchronousQueue, LinkedBlockingQueue, ArrayBlockingQueue).
threadFactory – creates new threads.
14. Executor Rejection Policies
AbortPolicy – throws RejectedExecutionException.
DiscardPolicy – silently discards the task.
DiscardOldestPolicy – discards the oldest queued task.
CallerRunsPolicy – runs the task in the calling thread.
Custom – implement RejectedExecutionHandler.
15. Common ThreadPool Types
newSingleThreadExecutor – single‑threaded executor.
newCachedThreadPool – creates threads as needed and reuses idle ones.
newFixedThreadPool – fixed number of threads.
newScheduledThreadPool – supports delayed and periodic tasks.
16. CopyOnWriteArrayList
Writes copy the underlying array, allowing lock‑free reads; suitable when reads vastly outnumber writes.
17. AbstractQueuedSynchronizer (AQS)
AQS uses an integer state and a FIFO queue of nodes to manage exclusive and shared synchronizers.
private volatile int state; // shared variable, volatile ensures visibility18. BlockingQueue Implementations
ArrayBlockingQueue
LinkedBlockingQueue
PriorityBlockingQueue
DelayQueue
SynchronousQueue
LinkedTransferQueue
LinkedBlockingDeque
19. Condition Interface
Condition provides a simpler, single‑direction wait queue compared to the built‑in monitor queue.
20. Fork/Join Framework
Fork/Join splits large tasks into smaller subtasks (RecursiveAction or RecursiveTask) and executes them in a work‑stealing pool.
21. Atomic Classes
Java provides atomic primitives for basic types (AtomicBoolean, AtomicInteger, AtomicLong), arrays (AtomicIntegerArray, etc.), references (AtomicReference), and field updaters (AtomicIntegerFieldUpdater, etc.).
22. CyclicBarrier
CyclicBarrier blocks a set of threads until all have called await(), then releases them simultaneously; it can be reset for reuse.
23. Semaphore
Semaphore limits concurrent access to a resource, useful for flow control such as limiting database connections.
24. Deadlock and Prevention
Deadlock requires mutual exclusion, hold‑and‑wait, no preemption, and circular wait. Prevention strategies include avoiding one of these conditions, resource ordering, or using the Banker's algorithm.
25. Inter‑Process Communication (IPC)
Common IPC mechanisms: pipe, named pipe, semaphore, message queue, signal, shared memory, socket.
26. Thread Interruption
interrupt() sets the interrupt flag; if the thread is blocked in wait/sleep/join, an InterruptedException is thrown and the flag is cleared. isInterrupted() checks the flag, while interrupted() checks and clears it.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
21CTO
21CTO (21CTO.com) offers developers community, training, and services, making it your go‑to learning and service platform.
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.
