GamifiedGamified challengesPracticeRaceLeaderboardPricing

Learn data structures by watching them move, then doing it yourself. Press M anytime to toggle sound.

A product of Amypo Technologies, Coimbatore.

Learn

  • All topics
  • Learning path
  • How it works
  • About dotprep

Practice

  • Practice arena
  • Daily challenge
  • Gamified challenges
  • Race mode
  • Leaderboard

Interview prep

  • Java interview
  • Coding questions
  • Company questions
  • System design
  • Jobs & careers

You

  • Dashboard
  • Settings
  • Pricing
  • Create account

© 2026 dotprep

Content last updated 20 November 2026

GamifiedGamified challengesPracticeRaceLeaderboardPricing
Java interviewMultithreading & concurrency

Multithreading & concurrency

Threads, synchronization, volatile, executors, deadlocks and CompletableFuture: the most-asked senior Java topic.

advanced 24 min read 9 interview questions

On this page

1/7
  1. 01Creating threads
  2. 02Race conditions and synchronized
  3. 03volatile and visibility
  4. 04Executors, Futures and CompletableFuture
  5. 05Deadlock, wait/notify and producer-consumer
  6. 06Interview questions
  7. 07Quick check
Back to top

Creating threads

A thread is an independent path of execution sharing the process's heap. Prefer passing a Runnable (or Callable) to a thread or executor over subclassing Thread: it separates the task from how it runs.

java
Runnable task = () -> System.out.println("hi from " + Thread.currentThread().getName());
Thread t = new Thread(task);
t.start(); // start() creates a new thread; run() would just run on the current one
t.join(); // wait for it to finish
// Java 21: virtual threads, cheap enough to run millions
Thread.startVirtualThread(task);
StateMeaning
NEWCreated, not started
RUNNABLERunning or ready to run
BLOCKEDWaiting for a monitor lock
WAITING / TIMED_WAITINGIn wait(), join(), sleep(), park()
TERMINATEDFinished

Race conditions and synchronized

count++ is three steps (read, add, write). Two threads can read the same value and both write back the same result, losing an update. That's a race condition.

java
class Counter {
private int count;
public synchronized void increment() { count++; } // one thread at a time per object
public synchronized int get() { return count; }
}
// Or lock-free:
AtomicInteger hits = new AtomicInteger();
hits.incrementAndGet(); // atomic compare-and-swap
  • synchronized methods lock this (static ones lock the Class); a synchronized (obj) block locks obj.
  • Locks are reentrant: a thread holding a lock can enter other blocks guarded by it.
  • Exiting a synchronized block publishes its writes to the next thread that takes the same lock (happens-before).

volatile and visibility

Without synchronization a thread may keep a stale cached copy of a field. volatile guarantees every read sees the latest write and prevents reordering around it. It does not make compound actions like count++ atomic.

java
class Worker implements Runnable {
private volatile boolean running = true; // stop flag seen immediately
public void stop() { running = false; }
public void run() { while (running) doWork(); }
}

Executors, Futures and CompletableFuture

Creating a thread per task is expensive. An ExecutorService keeps a pool of worker threads and a queue of tasks.

java
ExecutorService pool = Executors.newFixedThreadPool(4);
Future<Integer> f = pool.submit(() -> expensiveCount());
int n = f.get(); // blocks until done
pool.shutdown();
CompletableFuture<String> page = CompletableFuture
.supplyAsync(() -> fetch(url)) // runs on a pool
.thenApply(String::toUpperCase) // transform when ready
.exceptionally(e -> "fallback"); // recover from errors
String text = page.join();
  • newFixedThreadPool(n): n workers, unbounded queue.
  • newCachedThreadPool(): grows as needed; risky under load.
  • newScheduledThreadPool(n): delayed and periodic tasks.
  • In production, configure ThreadPoolExecutor directly with a bounded queue and a rejection policy.

Deadlock, wait/notify and producer-consumer

A deadlock happens when threads each hold a lock the other needs: T1 holds A and waits for B while T2 holds B and waits for A. Prevent it by always taking locks in the same global order, using tryLock with a timeout, or holding fewer locks.

java
BlockingQueue<Job> queue = new ArrayBlockingQueue<>(100); // bounded buffer
// producer
queue.put(job); // blocks when full
// consumer
Job next = queue.take(); // blocks when empty

Prefer java.util.concurrent tools (BlockingQueue, CountDownLatch, Semaphore, ConcurrentHashMap) over hand-written wait()/notify(). If you do use wait(), call it in a loop that re-checks the condition, while holding the lock.

See it animated

QueueCircular queue

Interview questions

Try answering out loud first, then open the model answer.

Q1What's the difference between start() and run()?beginner

start() asks the JVM to create a new thread that then calls run(). Calling run() directly just executes the method on the current thread; no concurrency happens.

Q2Runnable vs Callable?beginner

Runnable.run() returns nothing and can't throw checked exceptions. Callable.call() returns a value and may throw. Submitting a Callable to an executor gives a Future for the result.

Q3What does volatile guarantee? Is it enough for a counter?intermediate

Visibility (every read sees the latest write) and ordering (no reordering across the volatile access). It is not enough for count++, which is read-modify-write; use synchronized, a lock, or AtomicInteger.

Q4What is a deadlock and how do you prevent it?intermediate

Two or more threads each wait forever for a lock another one holds. It needs mutual exclusion, hold-and-wait, no preemption and a circular wait. Break the cycle: acquire locks in a fixed order, use tryLock with timeouts, keep lock scopes small, or avoid shared locks altogether.

Q5sleep() vs wait()?intermediate

Thread.sleep() pauses the thread and keeps any locks it holds. Object.wait() must be called while holding that object's monitor; it releases the lock and waits until notify()/notifyAll() (or a timeout), then re-acquires the lock.

Q6How does ConcurrentHashMap achieve thread safety without locking everything?advanced

Since Java 8 it uses CAS to insert into empty bins and locks only the first node of a bin for other updates, so threads writing different bins don't block each other. Reads are lock-free thanks to volatile fields. Resizing is done cooperatively by the threads that touch the map.

Q7What is a thread pool and why use one?intermediate

A fixed set of reusable worker threads that take tasks from a queue. It avoids the cost of creating threads per task, caps concurrency so the machine isn't overwhelmed, and gives you lifecycle control (shutdown, awaitTermination).

Q8What does CompletableFuture add over Future?advanced

Non-blocking composition: chain steps with thenApply/thenCompose, combine results with thenCombine or allOf, handle errors with exceptionally/handle, and complete it manually. A plain Future only offers a blocking get().

Q9What are virtual threads (Java 21)?advanced

Lightweight threads managed by the JVM rather than the OS. A blocking call parks the virtual thread and frees its carrier OS thread, so you can write simple blocking code and still run hundreds of thousands of concurrent tasks (ideal for I/O-heavy servers).

Quick check

Question 1

1.Is count++ atomic on a volatile int?

Question 2

2.Which releases the monitor lock while waiting?

Question 3

3.Simplest fix for a lost-update counter shared by threads:

Question 4

4.A good way to avoid deadlock:

0 of 4 answered

Java 8+ featuresJVM internals & garbage collection
Log inStart free