Java Concurrency Interview Questions and Answers: Wait/Notify, Locks, Volatile, AQS, Thread Pools, and More
This article provides a comprehensive overview of Java concurrency concepts for interview preparation, covering wait/notify mechanisms, atomicity, visibility, ordering, synchronized implementation, volatile semantics, Java Memory Model, AQS, lock characteristics, ReentrantLock, ReadWriteLock, thread pool configurations, and producer‑consumer patterns with code examples.
1. Object wait() and notify()
The wait() method puts the current thread into a waiting state until another thread calls notify() or notifyAll() to wake it up; notify() wakes a single waiting thread.
2. Concurrency Characteristics – Atomicity, Visibility, Ordering
Atomicity: an operation or group of operations either completes entirely or not at all.
Visibility: changes made by one thread to a shared variable become immediately visible to other threads.
Ordering: program execution follows the source code order without instruction reordering.
3. synchronized Implementation Principle
synchronized guarantees exclusive access to a method or block and ensures memory visibility of shared variables. Every object can act as a lock; the lock source depends on whether the method is static, instance, or a synchronized block.
At the bytecode level, monitorenter and monitorexit instructions are inserted at the start and end of synchronized blocks, and the JVM ensures each monitorenter has a matching monitorexit.
4. volatile Implementation Principle
volatile provides lightweight visibility guarantees without blocking; reads always see the latest write, and writes are atomic for 32‑bit types (long, double require special handling). The JVM uses memory barriers to prevent instruction reordering.
Typical use cases: state‑flag variables and double‑checked locking.
5. Java Memory Model (JMM)
JMM defines the interaction between thread working memory and main memory, ensuring visibility and ordering while allowing compiler and processor optimizations.
6. AbstractQueuedSynchronizer (AQS) Queue Synchronizer
AQS is the foundation for locks and synchronizers (e.g., ReentrantLock, Semaphore). It maintains a FIFO queue of nodes representing waiting threads; when a thread fails to acquire the lock, it is enqueued and blocked until the state is released.
AQS internally uses a CLH doubly‑linked queue.
7. Lock Characteristics
Reentrant: the same thread can acquire the lock multiple times.
Interruptible: Lock can respond to interrupts, unlike synchronized.
Fairness: optional ordering based on request sequence.
8. ReentrantLock
Implements the Lock interface via an internal Sync class with FairSync and NonFairSync implementations.
Condition
Used with Lock to implement wait/notify patterns via await() and signal().
9. ReentrantReadWriteLock
Provides separate read and write locks, allowing multiple concurrent readers but exclusive writers, supporting fairness and lock downgrading.
Implements ReadWriteLock; state stored in a 32‑bit int split into high 16 bits (read) and low 16 bits (write).
10. Differences Between synchronized and Lock
synchronized is a language keyword; Lock is an interface.
Lock offers interruptible acquisition, tryLock, and explicit unlocking.
synchronized automatically releases on exception; Lock requires manual release.
11. Thread Synchronization Methods
synchronized blocks/methods
volatile
java.util.concurrent.locks.Lock
ThreadLocal
BlockingQueue (e.g., LinkedBlockingQueue)
Atomic variables (java.util.concurrent.atomic)
Immutable objects
12. Compare‑And‑Swap (CAS)
CAS provides atomic read‑modify‑write without locking. Example pseudo‑code and Java implementation in AtomicInteger using Unsafe are shown.
if (this.value == A) { this.value = B; return true; } else { return false; }13. HashMap Thread Safety
HashMap is not thread‑safe; concurrent modifications can cause infinite loops. Thread‑safe alternatives include Hashtable, Collections.synchronizedMap, and ConcurrentHashMap.
14. ConcurrentHashMap Implementation
JDK 7 uses segmented locks; JDK 8 employs CAS and synchronized with a node array that transforms long chains into red‑black trees when size exceeds 8.
15. CountDownLatch vs. CyclicBarrier
CountDownLatch allows one or more threads to wait for a set of operations to complete; its count cannot be reset.
CyclicBarrier lets a fixed number of threads wait for each other and can be reused.
16. Reducing Context Switches
Lock‑free programming and CAS.
Minimize thread count.
Use coroutines.
17. Optimistic vs. Pessimistic Locks
Pessimistic locks (e.g., synchronized) assume conflicts; optimistic locks (e.g., CAS) assume no conflict and retry on failure.
18. Blocking Queues
Various implementations (ArrayBlockingQueue, LinkedBlockingQueue, PriorityBlockingQueue, DelayQueue, SynchronousQueue, LinkedTransferQueue, LinkedBlockingDeque) provide different blocking and ordering semantics.
19. Thread Pool States and Parameters
States: RUNNING, SHUTDOWN, STOP, TIDYING, TERMINATED. Core pool size, maximum pool size, keepAliveTime, workQueue, threadFactory, and rejection handler are configurable.
Common Executors
public static ExecutorService newFixedThreadPool(int nThreads) { return new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>()); } public static ExecutorService newCachedThreadPool() { return new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>()); }20. Why Use Thread Pools
Reuse threads to avoid creation overhead.
Control maximum concurrency.
Provide task scheduling features.
21. Producer‑Consumer Problem
Example implementation using Object.wait()/notifyAll() and alternatively ReentrantLock with Condition.
public class ProducerConsumer { /* code omitted for brevity */ }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.
Selected Java Interview Questions
A professional Java tech channel sharing common knowledge to help developers fill gaps. Follow us!
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.
