Top 50 Java Multithreading Interview Questions Every Developer Should Know
This article compiles 50 of the most frequently asked Java multithreading and concurrency interview questions, covering core concepts, thread creation, synchronization mechanisms, memory model, common pitfalls, and best practices, providing concise explanations to help both novice and experienced developers prepare effectively.
Whether you are a new programmer or a seasoned developer, you have likely encountered thread‑related questions in Java interviews. Java’s built‑in concurrency support makes it popular, and many high‑paying Java positions require strong multithreading skills.
1) What is a thread?
A thread is the smallest unit of execution that an operating system can schedule, existing within a process. It enables parallel processing on multi‑core CPUs, allowing tasks to be completed faster; Java provides excellent built‑in support for threads.
2) What is the difference between a thread and a process?
A process can contain many threads that run concurrently. Different processes have separate memory spaces, while all threads of a process share the same memory. Each thread also has its own stack for local variables.
3) How do you create a thread in Java?
You can either extend java.lang.Thread or implement the java.lang.Runnable interface and override its run method. The former creates a Thread object directly; the latter is preferred when you need to extend another class.
4) Should you use Runnable or Thread?
Because Java does not support multiple inheritance of classes, using Runnable is preferable when you also need to extend another class. Otherwise, extending Thread works as well.
6) What is the difference between start and run ?
startcreates a new thread and then internally calls run. Directly invoking run executes the code in the current thread without creating a new one.
7) What is the difference between Runnable and Callable ?
Runnablehas a run method that returns void and cannot throw checked exceptions. Callable (added in JDK 1.5) returns a value via call and can throw exceptions, producing a Future result.
8) Difference between CyclicBarrier and CountDownLatch ?
Both let a group of threads wait for others, but CountDownLatch cannot be reused after the count reaches zero, whereas CyclicBarrier can be reset and reused.
9) What is the Java Memory Model?
The Java Memory Model defines how threads interact through memory, guaranteeing visibility and ordering of reads/writes. It includes rules such as program order, monitor lock rule, volatile variable rule, thread start rule, thread termination rule, and object finalization rule.
10) What is a volatile variable?
volatilecan be applied only to member fields. It ensures that a write to the variable happens before any subsequent read, providing visibility guarantees without full synchronization.
11) What is thread safety? Is Vector thread‑safe?
A piece of code is thread‑safe if its behavior is correct when accessed by multiple threads simultaneously. Vector achieves thread safety by synchronizing its methods, whereas ArrayList is not thread‑safe.
12) What is a race condition? Give an example.
A race condition occurs when the outcome of a program depends on the unpredictable timing of thread execution, leading to bugs that are hard to reproduce.
13) How can you stop a thread in Java?
Modern Java discourages using the deprecated stop, suspend, and resume methods. Instead, let the thread exit naturally or use a shared volatile flag to break out of its run loop.
14) What happens if a thread throws an uncaught exception?
The thread terminates. You can handle such situations by setting a Thread.UncaughtExceptionHandler to process the exception.
15) How do you share data between two threads?
Share a common object or use concurrent data structures such as a blocking queue, which internally uses wait and notify to coordinate producer‑consumer scenarios.
16) Difference between notify and notifyAll ?
notifywakes a single waiting thread, while notifyAll wakes all waiting threads, allowing them to compete for the lock.
17) Why are wait , notify , and notifyAll defined in Object instead of Thread ?
Because Java’s lock is associated with every object, not with a thread. Placing these methods in Object lets any object act as a monitor.
18) What is a ThreadLocal variable?
ThreadLocalprovides a separate instance of a variable for each thread, eliminating contention. It is useful for making otherwise non‑thread‑safe objects (e.g., SimpleDateFormat) thread‑safe.
19) What is a FutureTask ?
FutureTaskrepresents a cancellable asynchronous computation. It can wrap a Callable or Runnable and be submitted to an Executor.
20) Difference between Thread.interrupted() and Thread.isInterrupted() ?
Thread.interrupted()clears the interrupt status after checking it, while isInterrupted() merely returns the status without clearing it.
21) Why must wait and notify be called inside a synchronized block?
Calling them outside a synchronized block throws IllegalMonitorStateException and can lead to race conditions.
22) Why check the waiting condition in a loop?
Because spurious wake‑ups can occur; the condition must be re‑evaluated after each wake‑up to ensure correctness.
23) Difference between synchronized collections and concurrent collections?
Synchronized collections lock the entire collection for each operation, causing contention. Concurrent collections (e.g., ConcurrentHashMap) use finer‑grained locking or lock‑free algorithms, offering better scalability.
24) Difference between heap and stack memory?
Each thread has its own stack for local variables and method frames, while the heap is shared among all threads for object allocation.
25) What is a thread pool and why use it?
Creating threads is expensive; a thread pool reuses a fixed number of worker threads to execute tasks, reducing overhead and improving responsiveness. Java provides several pool types via the Executor framework.
26) How to solve the producer‑consumer problem?
Use wait/notify, or preferably higher‑level constructs such as BlockingQueue or Semaphore to coordinate producers and consumers.
27) How to avoid deadlock?
Prevent circular wait by imposing a global ordering on resource acquisition, or use timeout‑based lock acquisition.
28) Difference between livelock and deadlock?
In a deadlock, threads are blocked waiting for each other. In a livelock, threads keep running but make no progress because they continually respond to each other’s actions.
29) How to detect if a thread holds a lock?
Use Thread.holdsLock(Object), which returns true if the current thread owns the monitor for the given object.
30) How to obtain a thread’s stack trace?
On Windows press Ctrl+Break; on Linux send kill -3 to the JVM process, or use the jstack tool.
31) Which JVM option controls thread stack size?
The -Xss flag sets the per‑thread stack size.
32) Difference between synchronized and ReentrantLock ?
ReentrantLockoffers more flexibility (e.g., try‑lock, interruptible lock acquisition) and can be unlocked outside the synchronized block, whereas synchronized is simpler but less feature‑rich.
33) How to enforce execution order of three threads T1, T2, T3?
Use Thread.join() so that T2 joins T1 and T3 joins T2, ensuring the desired sequence.
34) What does Thread.yield() do?
It hints to the scheduler that the current thread is willing to pause, allowing other threads of equal priority to run.
35) What is the concurrency level of ConcurrentHashMap ?
It is the number of segments (default 16) that the map is divided into, reducing contention among threads.
36) What is a Semaphore ?
A counting semaphore controls access to a set of permits; threads acquire a permit before proceeding and release it when done.
37) What happens when a thread pool’s queue is full?
The submit method throws RejectedExecutionException.
38) Difference between submit and execute ?
executereturns void, while submit returns a Future representing the task’s result.
39) What is a blocking method?
A method that does not return until its operation completes, e.g., ServerSocket.accept().
40) Is Swing thread‑safe? Why?
No. Swing components must be accessed only on the Event Dispatch Thread; otherwise race conditions may occur.
41) Difference between invokeAndWait and invokeLater ?
invokeAndWaitblocks until the GUI update finishes; invokeLater queues the update and returns immediately.
42) Which Swing methods are thread‑safe?
Methods such as repaint(), revalidate(), and certain JTextComponent methods are safe to call from other threads.
43) How to create an immutable object in Java?
Declare all fields as private final, provide no setters, initialize via constructor, and return defensive copies from getters.
44) What is ReadWriteLock ?
It provides separate locks for read‑only and write operations, allowing multiple concurrent readers while writes obtain exclusive access.
45) What is a busy‑wait loop?
A loop that repeatedly checks a condition without yielding the CPU, often used to keep data in cache but generally discouraged.
46) Difference between volatile and atomic variables?
volatileguarantees visibility but not atomicity; atomic classes (e.g., AtomicInteger) provide lock‑free atomic operations.
47) What happens if an exception is thrown inside a synchronized block?
The lock is automatically released when the block exits, even if an exception occurs.
48) What is double‑checked locking for a singleton?
It lazily creates a singleton instance with a synchronized block guarded by a null check, but requires the volatile keyword (since Java 1.5) to avoid reordering issues.
49) How to create a thread‑safe singleton?
Use static initialization, an enum, or the initialization‑on‑demand holder idiom to ensure safe publication.
50) Three best practices for multithreaded code
Give threads meaningful names to aid debugging.
Minimize the scope of synchronized blocks and avoid unnecessary locking.
Prefer high‑level concurrency utilities (e.g., CountDownLatch, Semaphore, CyclicBarrier) over raw wait / notify.
Prefer concurrent collections over synchronized ones.
These practices help write clearer, more efficient, and less error‑prone concurrent Java programs.
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.
21CTO
21CTO (21CTO.com) offers developers community, training, and services, making it your go‑to learning and service platform.
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.
