Java Concurrency
Where senior rounds are decided. Every question here has a wrong answer that sounds correct, and correctness cannot be established by running it once.
9 concepts · 26 interview questions
What this topic covers
Every concept in concurrency, and the questions each one gets asked as. Where a question links, it has a full write-up.
Threads and lifecycle
A thread is an OS-scheduled unit of execution with a defined state machine. Creating them directly is almost always the wrong level of abstraction.
- What are the states in a thread's lifecycle?
- What is the difference between start() and run()?
- Runnable vs Callable?
Races, atomicity and visibility
Three separate problems. count++ is not atomic; volatile fixes visibility and ordering but never atomicity.
- What does volatile guarantee, and what does it not?
- Why is count++ not thread-safe?
- What is a race condition, precisely?
The Java memory model
happens-before is the only correct reasoning tool. Without an ordering edge, one thread's write is not guaranteed visible to another at all.
- What is the happens-before relationship?
- What does the JMM guarantee about final fields?
- Is double-checked locking safe?
synchronized and locks
A monitor protects whatever you consistently guard with it. Lock scope and lock ordering are what decide contention and deadlock.
- AtomicInteger, synchronized, or ReentrantLock?
- What causes a deadlock and how do you prevent it?
- What is the difference between synchronized and ReentrantLock?
Concurrent collections
ConcurrentHashMap locks per bin and reads without locking; synchronizedMap takes one monitor over the whole map.
- Is HashMap thread-safe on modern Java?
- How does ConcurrentHashMap achieve thread safety?
- When would you use a BlockingQueue?
Executors and thread pools
A pool decouples task submission from thread management. An unbounded queue turns it into a memory leak whose rejection policy never fires.
- How do you size and shut down a thread pool?
- What happens when a thread pool's queue is full?
- Why is Executors.newFixedThreadPool risky by default?
CompletableFuture
Composable asynchronous results. thenApply versus thenApplyAsync decides which thread runs your callback, and the default is often the wrong one.
- How do you compose asynchronous work with CompletableFuture?
- What is the difference between thenApply and thenApplyAsync?
- How do you handle a failure in a CompletableFuture chain?
Virtual threads
Cheap threads scheduled by the JVM, which fix blocking I/O concurrency and do nothing for CPU-bound work.
- What are virtual threads, and when do they not help?
- What is thread pinning?
- Do virtual threads make thread pools obsolete?
ThreadLocal
Per-thread state that survives as long as the thread does — which in a pool is forever, and that is the leak.
- How does ThreadLocal leak memory in a thread pool?
- What is ThreadLocal legitimately used for?