Comprehensive Java Multithreading and Concurrency Interview Questions and Answers
This article compiles 46 essential Java multithreading and concurrency interview questions with detailed answers, covering fundamentals such as atomicity, visibility, ordering, thread creation methods, thread pools, synchronization mechanisms, lock types, AQS, deadlocks, and performance considerations for high‑performance backend development.
1. Concurrency programming three essential aspects
Atomicity: operations must be indivisible; Visibility: changes to shared variables must be immediately visible to other threads; Ordering: program execution follows the written code order.
2. Value of multithreading
It leverages multi‑core CPUs, prevents blocking by allowing other threads to continue when one thread waits, and simplifies modeling of complex tasks by decomposing them into smaller concurrent subtasks.
3. Ways to create threads
1) Extend the Thread class; 2) Implement the Runnable interface; 3) Use Callable with Future.
4. Comparison of thread‑creation approaches
Runnable/Callable allows sharing a target object and multiple inheritance, but requires explicit thread retrieval via Thread.currentThread(); extending Thread is simpler but prevents extending other classes.
5. Differences between Runnable and Callable
Runnable defines run() and returns no value; Callable defines call() and can return a result.
Callable can throw checked exceptions; Runnable cannot.
Callable tasks produce a Future object for result retrieval, cancellation, and status checking.
6. Thread lifecycle states
New, Runnable, Running, Blocked (waiting, synchronized, or other), and Dead.
7. Thread pool concepts and creation methods
A thread pool reuses a fixed set of threads to avoid the overhead of frequent creation and destruction. Java provides four main factories: newCachedThreadPool, newFixedThreadPool, newScheduledThreadPool, and newSingleThreadExecutor.
8. Advantages of thread pools
Reuse existing threads, control maximum concurrency, and offer scheduling capabilities.
9. Synchronized collections vs. concurrent collections
Synchronized collections (Vector, Stack, Hashtable, Collections.synchronized*) lock the entire structure; concurrent collections (ConcurrentHashMap, CopyOnWriteArrayList/Set) use finer‑grained locking for higher scalability.
10. Common concurrency utilities
CountDownLatch
CyclicBarrier
Semaphore
Exchanger
11. CountDownLatch vs. CyclicBarrier
CountDownLatch allows one or more threads to wait for a set of operations to complete; CyclicBarrier makes a group of threads wait for each other before proceeding, and can be reset for reuse.
12. Synchronization primitives comparison
synchronized (pessimistic lock, blocking), volatile (visibility and ordering), CAS (optimistic non‑blocking lock).
13. Differences between sleep() and wait()
sleep() does not release the object's monitor; wait() releases the monitor and must be called within a synchronized block.
14. ThreadLocal purpose
Provides thread‑confined variables, enabling stateless, high‑concurrency code by storing data in a per‑thread map.
15. Lock vs. synchronized
Lock (e.g., ReentrantLock) offers features such as timed tryLock, interruptible acquisition, and multiple condition objects, whereas synchronized is a built‑in keyword with simpler semantics.
16. Optimistic vs. pessimistic locking
Optimistic (CAS) assumes low contention and retries on failure; pessimistic (synchronized) assumes contention and acquires an exclusive lock.
17. AQS (AbstractQueuedSynchronizer)
Foundation for many Java synchronizers (ReentrantLock, Semaphore, CountDownLatch, etc.) supporting exclusive and shared modes.
18. ReadWriteLock
Allows multiple concurrent reads while writes acquire an exclusive lock, improving read‑heavy workload performance.
19. FutureTask
Wraps a Callable for asynchronous execution; implements Runnable so it can be submitted to an ExecutorService.
20. Thread scheduling and time slicing
The OS scheduler selects the highest‑priority runnable thread; pre‑emptive scheduling and time slicing share CPU among threads.
21. Spin‑waiting
For short critical sections, threads may busy‑wait (spin) instead of blocking, reducing context‑switch overhead.
22. Singleton thread‑safety
Eager initialization is thread‑safe; lazy initialization requires double‑checked locking or other synchronization.
23. Semaphore usage
Controls concurrency by limiting the number of threads that can access a resource simultaneously.
24. Executors utility class
Provides factory methods for creating thread pools and other executor services.
25. Thread creation overhead and limits
Creating too many threads increases memory usage, CPU contention, and can cause OutOfMemoryError due to OS or JVM limits.
26. Handling full thread‑pool queues
Unbounded queues accept all tasks; bounded queues trigger RejectedExecutionHandler policies (e.g., AbortPolicy) when both the queue and maximum pool size are exhausted.
27. Deadlock causes and avoidance Deadlocks arise from circular lock dependencies; avoid by acquiring locks in a consistent order, minimizing lock scope, and using timeout‑based locks. 28. Waking a blocked thread Interrupt the thread (throws InterruptedException) for wait/sleep/join; I/O‑blocked threads cannot be directly awakened from Java code. 29. Immutable objects in multithreading Immutable objects guarantee visibility without additional synchronization, improving performance. 30. Context switching overhead Switching CPU control between threads incurs kernel‑mode transitions, affecting performance. 31. Concurrency level of ConcurrentHashMap Determined by the number of segments (default 16), allowing up to 16 threads to modify the map concurrently. 32. Linux thread CPU usage inspection Use jps or ps -ef | grep java to find the PID, then top -H -p <pid> to view per‑thread CPU consumption.
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.
Mike Chen's Internet Architecture
Over ten years of BAT architecture experience, shared generously!
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.
