40 Common Java Multithreading Interview Questions and Answers

This article compiles and answers 40 frequently asked Java multithreading interview questions, covering thread purpose, creation methods, key APIs, synchronization mechanisms, thread safety levels, performance considerations, and practical debugging techniques for developers seeking a solid understanding of concurrent programming.

Java Architect Essentials
Java Architect Essentials
Java Architect Essentials
40 Common Java Multithreading Interview Questions and Answers

40 Common Java Multithreading Interview Questions

Purpose of multithreading : Utilizes multiple CPU cores to improve performance, prevents blocking on I/O, and simplifies modeling of complex tasks by decomposing them into independent subtasks.

1. How to create a thread

Two common ways: extend Thread or implement Runnable. Implementing Runnable is preferred because it promotes loose coupling and follows the principle of programming to an interface.

2. Difference between start() and run()

start()

initiates a new thread and executes run() concurrently; calling run() directly runs the code synchronously in the current thread.

3. Runnable vs Callable

Runnable

returns void; Callable returns a generic result via Future, allowing retrieval or cancellation of asynchronous computation.

4. CyclicBarrier vs CountDownLatch

CyclicBarrier

makes threads wait until all have reached the barrier and can be reused; CountDownLatch decrements a count and cannot be reset.

5. Role of volatile

Ensures visibility of variable updates across threads and prevents certain reordering optimizations, though it does not guarantee atomicity.

6. What is thread‑safety

A class is thread‑safe if it produces the same result when executed by multiple threads as when executed by a single thread. Levels include immutable objects, absolute thread‑safety, relative thread‑safety, and non‑thread‑safe classes.

7. Obtaining a thread dump

Use jps (or ps -ef | grep java) to get the PID, then jstack PID (or send SIGQUIT with kill -3 PID) to print stack traces. Thread.getStackTrace() can also be called programmatically.

8. Uncaught runtime exception in a thread

The thread terminates and any monitor it holds is released.

9. Sharing data between threads

Share objects and coordinate via wait/notify, await/signal, or concurrent collections such as BlockingQueue.

10. Difference between sleep() and wait()

sleep()

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

11. Purpose of the producer‑consumer model

Balances production and consumption rates to improve throughput and decouples producers from consumers.

12. Use of ThreadLocal

Provides thread‑confined storage, eliminating the need for synchronization on that data.

13. Why wait() and notify() must be called inside synchronized blocks

They require the calling thread to hold the object's monitor.

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

wait()

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

15. Benefits of thread pools

Reuse threads to avoid the overhead of creation/destruction and allow configurable concurrency limits.

16. Detecting if a thread holds a monitor

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

17. synchronized vs ReentrantLock

ReentrantLock

is a class offering more features (timeout, interruptibility, fairness) whereas synchronized is a language keyword.

18. Concurrency level of ConcurrentHashMap

Determined by the number of segments (default 16), allowing that many threads to modify the map concurrently.

19. What is ReadWriteLock

Provides a shared read lock and an exclusive write lock, improving performance for read‑heavy workloads.

20. Role of FutureTask

Wraps a Callable so it can be executed as a Runnable and its result retrieved later.

21. Finding the CPU‑intensive thread on Linux

Obtain the Java process PID, then run top -H -p PID to see per‑thread CPU usage; correlate LWP (decimal) with Java thread IDs (hex) from jps.

22. Example of a deadlock program

Two threads each lock two objects in opposite order (lock1 then lock2 vs lock2 then lock1), causing circular waiting.

23. Waking a blocked thread

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

24. How immutable objects help multithreading

They guarantee visibility without synchronization, improving read performance.

25. What is a context switch

CPU switches execution from one running thread to another ready thread.

26. Thread pool behavior when the queue is full

Unbounded queues (e.g., LinkedBlockingQueue) accept all tasks; bounded queues (e.g., ArrayBlockingQueue) invoke the configured RejectedExecutionHandler, defaulting to AbortPolicy.

27. Java thread scheduling algorithm

Preemptive scheduling based on thread priority, starvation, and time‑slice allocation.

28. Effect of Thread.sleep(0)

Hints the scheduler to yield the current time slice, allowing other threads a chance to run.

29. What is spinning

Busy‑waiting (looping) for a lock instead of blocking, useful for very short critical sections.

30. Overview of the Java Memory Model (JMM)

Defines main memory vs. working memory, atomic actions, volatile semantics, and the happens‑before relationship that determines visibility and ordering guarantees.

31. What is CAS (Compare‑And‑Set)

An atomic primitive that updates a memory location only if it matches an expected value, often used with volatile variables.

32. Optimistic vs. pessimistic locking

Optimistic locking assumes conflicts are rare and uses CAS; pessimistic locking assumes conflicts are common and acquires exclusive locks.

33. What is AQS (AbstractQueuedSynchronizer)

Core framework for building synchronizers (e.g., ReentrantLock, CountDownLatch, Semaphore) using a FIFO wait queue.

34. Thread‑safe singleton patterns

Eager initialization (always safe), lazy initialization (unsafe without synchronization), and double‑checked locking (safe with volatile).

35. Role of Semaphore

Limits concurrent access to a resource to a specified number of permits; a single permit behaves like a mutex.

36. Why Hashtable.size() is synchronized

To ensure a consistent view of the count when other threads may be modifying the map concurrently.

37. Which thread runs a class’s constructor and static block

The thread that creates the class instance runs the constructor and static initializer; the thread’s run() method executes the thread’s own code.

38. Synchronized method vs. synchronized block

Synchronized blocks are generally preferred because they limit the locked region, reducing contention; the JVM may also perform lock‑coarsening for performance.

39. Thread‑pool sizing guidelines

• High concurrency, short tasks: pool size ≈ CPU cores + 1. • Low concurrency, long I/O‑bound tasks: increase pool size beyond cores. • High concurrency, long CPU‑bound tasks: keep pool size modest to avoid excessive context switches. • For long‑running workloads, consider architectural changes such as caching or task decomposition.

© java架构师历程 – a platform providing high‑quality Java articles for engineers.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

concurrencyThreadPoolThreadSynchronizationmultithreadinginterview
Java Architect Essentials
Written by

Java Architect Essentials

Committed to sharing quality articles and tutorials to help Java programmers progress from junior to mid-level to senior architect. We curate high-quality learning resources, interview questions, videos, and projects from across the internet to help you systematically improve your Java architecture skills. Follow and reply '1024' to get Java programming resources. Learn together, grow together.

0 followers
Reader feedback

How this landed with the community

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.