Fundamentals 29 min read

40 Common Java Multithreading Interview Questions and Answers

This article presents a comprehensive collection of 40 Java multithreading interview questions, covering the purpose of multithreading, thread creation methods, differences between start() and run(), Runnable vs Callable, synchronization utilities, memory model, locks, thread pools, and best practices for concurrent programming.

Qunar Tech Salon
Qunar Tech Salon
Qunar Tech Salon
40 Common Java Multithreading Interview Questions and Answers

These multithreading questions are gathered from various websites and personal reflections; the author answers each based on personal understanding without consulting online answers.

40 Questions Summary

1. What is the purpose of multithreading?

Multithreading leverages multi‑core CPUs to utilize CPU resources fully, prevents blocking by allowing other threads to continue when one thread is waiting for I/O, and simplifies modeling by decomposing large tasks into smaller concurrent tasks.

2. Ways to create a thread

Common approaches are (1) extending the Thread class and (2) implementing the Runnable interface; the latter is preferred because it promotes interface‑based programming and reduces coupling.

3. Difference between start() and run()

Only start() initiates a new thread and enables concurrent execution; calling run() directly executes the code synchronously in the current thread.

4. Difference between Runnable and Callable

Runnable 's run() returns void , while Callable 's call() returns a value and can be used with Future / FutureTask to obtain results or cancel execution.

5. Difference between CyclicBarrier and CountDownLatch

CyclicBarrier makes threads wait until all have reached a barrier before proceeding, is reusable, and can trigger a single task; CountDownLatch decrements a counter, is not reusable, and can release multiple waiting threads.

6. Role of the volatile keyword

volatile guarantees visibility of variable updates across threads and prevents certain instruction reorderings, though it does not provide atomicity.

7. What is thread safety?

Code is thread‑safe if it produces the same result when executed concurrently as when executed sequentially. Levels include immutable objects, absolutely thread‑safe classes, relatively thread‑safe classes (e.g., Vector ), and non‑thread‑safe classes (e.g., ArrayList ).

8. How to obtain a thread dump in Java

Use jps to get the PID, then jstack PID or kill -3 PID to print stack traces; alternatively, Thread.getStackTrace() can retrieve a specific thread's stack.

9. What happens if a thread throws an uncaught runtime exception?

The thread terminates, and any monitor it holds is released immediately.

10. How to share data between two threads

Share an object and use coordination mechanisms such as wait/notify or concurrent collections like BlockingQueue .

11. Difference between sleep() and wait()

sleep() pauses the thread without releasing its monitor; wait() releases the monitor and waits to be notified.

12. Purpose of the producer‑consumer model

It balances production and consumption rates to improve system throughput and decouples producers from consumers.

13. What is ThreadLocal used for?

ThreadLocal provides thread‑confined storage, eliminating the need for synchronization by keeping data isolated per thread.

14. Why must wait() and notify() be called inside a synchronized block?

Because the JVM requires the calling thread to hold the object's monitor before invoking these methods.

15. Difference in monitor release between wait() and notify()

wait() releases the monitor immediately; notify() releases it only after the synchronized block completes.

16. Why use a thread pool?

To reuse thread objects, avoid the overhead of frequent creation/destruction, and control the level of concurrency.

17. How to detect if a thread holds a monitor

Use Thread.holdsLock(Object obj) , which returns true only for the current thread.

18. Difference between synchronized and ReentrantLock

synchronized is a language keyword; ReentrantLock is a class offering more flexible features such as timed lock acquisition, lock inspection, and multiple condition variables.

19. What is the concurrency level of ConcurrentHashMap ?

The concurrency level equals the number of segments (default 16), allowing up to 16 threads to modify the map concurrently.

20. What is ReadWriteLock ?

It separates read and write locks: read locks are shared, write locks are exclusive, improving performance when reads dominate.

21. What is FutureTask ?

FutureTask represents an asynchronous computation; it implements Runnable and can be submitted to an executor, providing methods to retrieve results, check completion, or cancel.

22. How to find the thread that uses the most CPU on Linux

Obtain the PID with jps or ps , then run top -H -p PID to see per‑thread CPU usage; match the LWP (decimal) with the Java thread ID (hex) to locate the offending thread.

23. Example of a deadlock program in Java

Two threads each lock two objects in opposite order (e.g., lock1 then lock2 vs. lock2 then lock1) after a short sleep, causing a circular wait and deadlock.

24. How to wake a blocked thread

Interrupt the thread, causing an InterruptedException for wait() , sleep() , or join() ; I/O‑blocked threads cannot be awakened directly from Java.

25. How immutable objects help multithreading

Immutable objects guarantee visibility without synchronization, improving performance.

26. What is a context switch in multithreading?

A context switch occurs when the CPU switches execution from one running thread to another ready thread.

27. What happens when a thread pool’s queue is full?

With an unbounded LinkedBlockingQueue , tasks are queued indefinitely; with a bounded queue (e.g., ArrayBlockingQueue ), the configured RejectedExecutionHandler handles overflow, defaulting to AbortPolicy .

28. Thread scheduling algorithm used by Java

Preemptive scheduling based on thread priority, starvation, and other factors.

29. Effect of Thread.sleep(0)

It yields the processor, prompting the OS to perform a context switch and give other threads a chance to run.

30. What is spinning?

Spinning is a busy‑wait loop where a thread repeatedly checks for a lock instead of blocking, reducing kernel‑mode transitions for short‑duration critical sections.

31. What is the Java Memory Model?

The JMM defines how threads interact with memory, distinguishing main memory and working memory, specifying atomic operations, volatile semantics, and the happens‑before ordering rules.

32. What is CAS (Compare‑And‑Swap)?

CAS atomically updates a memory location from an expected value A to a new value B only if the current value V equals A , returning true on success.

33. Optimistic vs. pessimistic locking

Optimistic locking assumes conflicts are rare and uses CAS with retry logic; pessimistic locking assumes conflicts are common and acquires exclusive locks (e.g., synchronized ).

34. What is AQS (AbstractQueuedSynchronizer)?

AQS is the core framework for Java’s concurrency utilities, providing a FIFO wait queue and abstract methods tryAcquire / tryRelease that concrete synchronizers (e.g., ReentrantLock , CountDownLatch ) implement.

35. Thread‑safety of singleton patterns

Thread‑safe singleton implementations include the eager (static) initialization and double‑checked locking; lazy initialization without synchronization is not thread‑safe.

36. Purpose of Semaphore

Semaphore limits the number of concurrent accesses to a code block; a permit count of 1 behaves like a binary lock (similar to synchronized ).

37. Why does Hashtable.size() need synchronization?

Even a single‑line method can be interrupted between low‑level instructions; synchronization ensures a consistent view of count amid concurrent modifications.

38. Which thread invokes a thread class’s constructor and static block?

The thread that creates the instance (via new ) runs the constructor and static initializer; the run() method is executed by the new thread itself.

39. Synchronized method vs. synchronized block

Synchronized blocks are preferred because they limit the locked region, improving concurrency; however, the JVM may perform lock‑coarsening for performance in some cases.

40. Thread‑pool configuration for different workloads

For high‑concurrency short‑task workloads, set pool size to CPU cores + 1 . For low‑concurrency long‑running I/O‑bound tasks, increase pool size; for CPU‑bound long tasks, keep the pool size modest. For high‑concurrency long‑running tasks, focus on architecture (caching, scaling) and adjust the pool size accordingly.

Source: "java一日一条".

JavaconcurrencyThreadPoolthreadSynchronizationmultithreadingJava Memory Model
Qunar Tech Salon
Written by

Qunar Tech Salon

Qunar Tech Salon is a learning and exchange platform for Qunar engineers and industry peers. We share cutting-edge technology trends and topics, providing a free platform for mid-to-senior technical professionals to exchange and learn.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.