Java Interview Questions

Multithreading Interview Questions

Master concurrency with 40 in-depth Java multithreading interview questions covering threads, synchronization, locks, executors, and concurrent collections.

By TechCoder TeamLast updated: 2026-06-23
In a Nutshell

Master concurrency with 40 in-depth Java multithreading interview questions covering threads, synchronization, locks, executors, and concurrent collections. This interview-focused guide covers essential multithreading interview questions concepts for technical interviews.

Multithreading Interview Questions

Multithreading is a high-stakes interview topic. These 40 questions range from thread lifecycle basics to the executor framework, concurrent collections, and deadlock prevention — everything you need to ace the concurrency round.


1. Process vs Thread?

  • Process: Independent program execution. Has its own memory space. Heavy.
  • Thread: Lightweight unit within a process. Shares memory (heap).

2. Difference between wait() and sleep()?

Featurewait()sleep()
ClassObject classThread class
LockReleases lockKeeps lock
ActionWaits for notify()Waits for time
UsageInter-thread communicationPausing execution

3. What is a Deadlock?

A situation where two threads are blocked forever, waiting for each other to release a lock. Conditions:

  1. Mutual Exclusion
  2. Hold and Wait
  3. No Preemption
  4. Circular Wait

4. What is volatile keyword?

Indicates that a variable's value will be modified by different threads. Ensures visibility (changes are immediately flushed to main memory), but not atomicity.

5. synchronized block vs method?

  • Block: Locks only a specific section of code. More efficient.
  • Method: Locks the entire method.

6. What is ThreadLocal?

Creates variables that can solely be read/written by the same thread. Useful for storing user sessions, transaction IDs accessible anywhere in that thread.

7. Describe the Executor Framework?

Separates task submission from execution.

  • FixedThreadPool: Reuses fixed number of threads.
  • CachedThreadPool: Creates new threads as needed, reuses idle ones.
  • ScheduledThreadPool: Runs tasks periodically.

8. What is the difference between Runnable and Callable?

FeatureRunnableCallable
Return valuevoidCan return value
ExceptionCannot throw checkedCan throw checked
Methodrun()call()
UsageThread, ExecutorExecutorService
FutureNo (need FutureTask)Returns Future
Callable<String> task = () -> "Result from thread";
Future<String> future = executor.submit(task);
String result = future.get(); // blocking call

9. What is a Future?

A Future represents the result of an asynchronous computation. Methods:

  • get() — blocks until result available
  • get(timeout, unit) — blocks with timeout
  • cancel() — attempts cancellation
  • isDone() — checks if completed
  • isCancelled() — checks if cancelled

[!CAUTION] future.get() blocks the calling thread. In microservices, consider CompletableFuture for non-blocking composition.

10. What is CompletableFuture?

CompletableFuture (Java 8+) extends Future with functional composition. Supports chaining, combining, and exception handling without blocking.

CompletableFuture.supplyAsync(() -> fetchUser())
    .thenApply(user -> enrichUser(user))
    .thenAccept(enriched -> saveUser(enriched))
    .exceptionally(ex -> { log(ex); return null; });

11. What is the difference between start() and run()?

  • start(): Creates a new thread and calls run() in that thread. Called once per thread.
  • run(): Executes in the current thread. Doesn't create a new thread. Can be called multiple times.

[!IMPORTANT] Calling run() directly does NOT start a new thread — it's just a normal method call. Always use start() for threading.

12. What is the Thread Lifecycle?

  1. New: Thread object created, start() not yet called
  2. Runnable: After start(), ready to run (waiting for CPU)
  3. Running: Actually executing
  4. Blocked/Waiting/Timed Waiting: Waiting for lock, wait(), sleep(), or I/O
  5. Terminated: run() method completes or uncaught exception

13. What are notify() and notifyAll()?

  • notify(): Wakes up ONE random waiting thread on the same object's monitor.
  • notifyAll(): Wakes up ALL waiting threads on the same object's monitor.
  • Always prefer notifyAll() unless you have a very specific reason for notify(), to avoid missed signals.

14. What is the join() method?

join() makes the calling thread wait until the thread on which join() is called completes (dies). Useful for sequential execution of parallel tasks.

Thread t1 = new Thread(task);
t1.start();
t1.join();  // Main thread waits for t1 to finish

15. What is the yield() method?

yield() hints to the scheduler that the current thread is willing to pause, giving other threads of the same priority a chance. It's a hint, not a guarantee. Rarely used in practice.

16. What is a Daemon Thread?

A daemon thread is a low-priority background thread (e.g., garbage collector). JVM exits when all non-daemon threads finish. Daemon threads are abruptly terminated. Set with setDaemon(true) before start().

17. What is ThreadGroup?

ThreadGroup groups multiple threads for collective operations (interrupt all, set max priority). Rarely used in modern Java. Executor Framework is preferred.

18. What is a race condition?

A race condition occurs when multiple threads access shared data simultaneously, and the outcome depends on the timing/order of execution. Results in inconsistent or incorrect data.

// Race condition: counter++ is not atomic
// Thread1: read(0) → increment → write(1)
// Thread2: read(0) → increment → write(1)  // Lost update!

19. How to prevent race conditions?

  • synchronized keyword (mutual exclusion)
  • AtomicInteger, AtomicLong (CAS-based)
  • Lock interfaces (ReentrantLock)
  • volatile for visibility (not for compound actions)
  • Immutable objects

20. What are atomic classes?

Java's java.util.concurrent.atomic package provides lock-free, thread-safe operations on single variables using CAS (Compare-And-Swap):

  • AtomicInteger, AtomicLong, AtomicBoolean
  • AtomicReference, AtomicIntegerArray
  • LongAdder, DoubleAdder (better for high contention)
AtomicInteger counter = new AtomicInteger(0);
counter.incrementAndGet();  // Thread-safe increment

21. What is CAS (Compare-And-Swap)?

CAS is a lock-free atomic instruction: compares current value with expected value; if equal, swaps with new value. If not equal, retries (spin lock). Basis of atomic classes. Hardware-supported on most CPUs.

22. What is a ReentrantLock?

ReentrantLock is an explicit lock alternative to synchronized. Features:

  • Fairness: Can create fair locks (FIFO)
  • tryLock(): Non-blocking attempt
  • lockInterruptibly(): Interruptible lock acquisition
  • Condition: Multiple wait sets per lock
  • Always unlock in finally block!
Lock lock = new ReentrantLock();
lock.lock();
try {
    // critical section
} finally {
    lock.unlock();  // MUST unlock!
}

23. synchronized vs ReentrantLock?

FeaturesynchronizedReentrantLock
Lock acquisitionBlocking onlyBlocking, tryLock, interruptible
FairnessNoYes (optional)
ConditionOne implicitMultiple Condition objects
FlexibilityLessMore
PerformanceAdequateBetter under high contention
SyntaxSimpleVerbose (try-finally)

24. What is a ReadWriteLock?

ReadWriteLock maintains a pair of locks: one for read-only and one for writing. Multiple readers can hold read lock simultaneously; write lock is exclusive. Improves concurrency for read-heavy workloads.

ReadWriteLock rwLock = new ReentrantReadWriteLock();
rwLock.readLock().lock();   // Multiple readers allowed
rwLock.writeLock().lock();   // Exclusive writer

25. What is a Semaphore?

A Semaphore controls access to a shared resource through permits. Threads acquire permits before access and release them after.

Semaphore semaphore = new Semaphore(3); // 3 permits
semaphore.acquire();  // Takes 1 permit (blocks if none)
// ... use resource ...
semaphore.release();  // Returns 1 permit

26. What is a CountDownLatch?

CountDownLatch allows one or more threads to wait until a set of operations completes. Initialized with a count. countDown() decrements; when reaches zero, waiting threads proceed. One-time use.

CountDownLatch latch = new CountDownLatch(3);
// Threads: latch.await(); // wait
// Other threads: latch.countDown(); // decrement

27. What is a CyclicBarrier?

CyclicBarrier makes multiple threads wait for each other at a common barrier point. When all threads arrive, they're released. Reusable (cyclic). Optionally executes a barrier action.

CyclicBarrier barrier = new CyclicBarrier(3, () -> System.out.println("All ready!"));
// Each thread: barrier.await();

28. CountDownLatch vs CyclicBarrier?

FeatureCountDownLatchCyclicBarrier
ReusableNo (one-shot)Yes (cyclic)
PurposeThread(s) wait for eventsThreads wait for each other
CountingExternal threads countDownThreads themselves call await
ActionNoOptional barrier action
ResetNoYes (reset())

29. What is an Exchanger?

Exchanger is a synchronization point where two threads can exchange objects. Thread A gives X and gets Y; Thread B gives Y and gets X. Useful for producer-consumer with swap patterns.

30. What is a Phaser?

Phaser (Java 7+) is like a flexible, reusable CyclicBarrier + CountDownLatch. Can register/deregister parties dynamically. Supports tiered barriers.

31. What is the synchronized keyword?

synchronized ensures only one thread can execute a block/method at a time (mutual exclusion). Can be applied to:

  • Instance methods: Lock on this
  • Static methods: Lock on ClassName.class
  • Blocks: Lock on specified object

32. What is intrinsic lock (monitor)?

Every Java object has an intrinsic lock (monitor). When a thread enters a synchronized block, it acquires the object's intrinsic lock. Other threads block until the lock is released. Supports reentrancy.

33. What is reentrant synchronization?

A thread that already holds a lock can re-acquire it without deadlocking itself. Both synchronized and ReentrantLock support reentrancy. This is why a synchronized method can call another synchronized method on the same object.

34. What is thread starvation?

Starvation happens when a thread is unable to gain regular access to shared resources and makes no progress. Causes: unfair lock priority, high-priority threads dominating. Solutions: fair locks, proper scheduling.

35. What is livelock?

Livelock is when two or more threads keep responding to each other's state changes without making progress. Unlike deadlock (blocked), threads are active but stuck in a loop. Example: two people trying to pass in a hallway, both stepping aside mirroring each other.

36. What is Callable and how is it different from Runnable?

Callable (Java 5) returns a result and can throw checked exceptions. Submitted to ExecutorService.submit(), returns a Future. Runnable can't return results or throw checked exceptions.

37. What is invokeAll() and invokeAny()?

  • invokeAll(Collection<Callable>): Executes all tasks, returns List of Futures when ALL complete.
  • invokeAny(Collection<Callable>): Executes all tasks, returns result of the FIRST successfully completed task. Cancels others.

38. What is the Fork/Join Framework?

Fork/Join (Java 7+) is designed for recursive, divide-and-conquer parallelism. Splits tasks recursively (fork) and combines results (join). Uses work-stealing: idle threads "steal" work from busy threads. ForkJoinPool.commonPool().

39. How to create threads in Java?

  1. Extend Thread class: Override run(), call start(). Not recommended (loses ability to extend other classes).
  2. Implement Runnable: Pass to Thread constructor. Preferred.
  3. Implement Callable: For tasks that return results.
  4. Executor Framework: Best practice for thread management.

40. What are best practices for multithreading?

  1. Prefer executors over raw Thread management
  2. Use concurrent collections instead of synchronized wrappers
  3. Minimize synchronized block scope for better throughput
  4. Use volatile for simple flags (not compound actions)
  5. Always unlock in finally when using explicit locks
  6. Avoid thread starvation with fair locks
  7. Never swallow InterruptedException — restore the interrupt status
  8. Use CompletableFuture for asynchronous composition
JAVA PLAYGROUND
⏳ Loading editor…

AI Mentor

Assistant

Confused about "Java multithreading interview concepts including threads, synchronization, locks, executors, deadlock, and concurrent collections"? Ask our AI mentor for a simplified explanation.

Quiz

Quiz

Question 1 of 3

Does sleep() release the lock?

Yes
No