Java Multithreading and Concurrency Interview Questions and Answers
15 questions on threads, synchronized, volatile, deadlocks, executors, CompletableFuture, locks, and virtual threads.
1. How do you create a thread in Java?
Implement Runnable (or Callable when you need a result) and pass it to a Thread or, better, an ExecutorService. Extending Thread works but ties the task to the threading mechanism. In modern code, prefer executors, or virtual threads in Java 21 and newer.
Thread t = new Thread(() -> System.out.println("hello from " + Thread.currentThread().getName())); t.start(); // start(), not run(), creates a new thread t.join();2. What is the difference between Runnable and Callable?
Runnable.run returns nothing and cannot throw checked exceptions. Callable.call returns a value and may throw checked exceptions. Submitting a Callable to an ExecutorService returns a Future that you can use to get the result or the exception.
3. What are the states of a thread?
NEW (created, not started), RUNNABLE (running or ready to run), BLOCKED (waiting to enter a synchronized block), WAITING (waiting indefinitely, for example in wait() or join()), TIMED_WAITING (waiting with a timeout, such as sleep), and TERMINATED (finished).
4. What does the synchronized keyword do?
It gives mutual exclusion: only one thread at a time can hold an object's monitor and run the synchronized code. It also gives visibility: changes made inside the block are visible to the next thread that acquires the same lock. A synchronized instance method locks this; a static synchronized method locks the Class object.
5. What does volatile do, and when is it enough?
volatile guarantees that writes to a variable are visible to other threads and prevents certain reordering. It does not make compound operations atomic, so count++ on a volatile field is still unsafe. It is suitable for simple flags (a stop signal) and safe publication, while counters need AtomicInteger or locking.
6. What is a race condition, and how do you prevent it?
A race condition occurs when the result depends on the unpredictable timing of threads, such as two threads doing a read-modify-write on the same field. Prevent it with synchronization, locks, atomic classes, immutable objects, or by avoiding shared mutable state with thread confinement.
7. What is a deadlock, and how can you avoid it?
A deadlock happens when threads wait for each other's locks forever. Typical cause: thread A holds lock 1 and wants lock 2 while thread B holds lock 2 and wants lock 1. Avoid it by always acquiring locks in a consistent global order, holding locks for as short a time as possible, using tryLock with a timeout, and preferring higher-level concurrency utilities. Thread dumps (jstack) help diagnose it.
8. What is an ExecutorService and why use it?
It separates task submission from thread management. A pool reuses threads instead of creating one per task, limits concurrency, queues extra work, and provides orderly shutdown. Create pools with Executors factories or ThreadPoolExecutor directly. Always call shutdown() when finished, and size pools to the workload (CPU-bound tasks near the core count, I/O-bound tasks higher).
9. What is CompletableFuture?
It represents an asynchronous result that you can compose without blocking: chain steps with thenApply and thenCompose, combine with thenCombine, wait for several with allOf, and handle errors with exceptionally or handle.
CompletableFuture<String> result = CompletableFuture .supplyAsync(() -> fetchUser(42)) .thenApply(user -> user.name()) .exceptionally(error -> "unknown");10. What are atomic classes and how do they work?
Classes such as AtomicInteger and AtomicReference provide lock-free thread-safe operations using hardware compare-and-swap (CAS). incrementAndGet either succeeds or retries, so no thread blocks. For heavily contended counters, LongAdder scales better.
11. What is the difference between synchronized and ReentrantLock?
Both are reentrant mutual-exclusion locks. ReentrantLock adds capabilities: tryLock, timed and interruptible lock attempts, optional fairness, and multiple Condition objects. The cost is that you must unlock in a finally block yourself. Use synchronized for simplicity and ReentrantLock when you need those extra features.
12. What is ThreadLocal?
It gives each thread its own independent copy of a variable, useful for per-thread context such as a user or transaction id, or a non-thread-safe helper. In thread pools you must call remove() when finished, or values leak into the next task that reuses the thread.
13. What do CountDownLatch, CyclicBarrier, and Semaphore do?
CountDownLatch lets threads wait until a count reaches zero and cannot be reset. CyclicBarrier makes a fixed group of threads wait for each other at a point and can be reused. Semaphore limits how many threads can use a resource at once by handing out permits.
14. What are virtual threads?
Introduced as a final feature in Java 21, virtual threads are lightweight threads managed by the JVM rather than the operating system. You can run huge numbers of them, and blocking calls such as I/O park the virtual thread cheaply. They suit high-concurrency, I/O-bound server code written in a simple blocking style. They do not make CPU-bound code faster.
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) { executor.submit(() -> handleRequest()); }15. What is the Java Memory Model's happens-before relationship?
It defines when one thread's writes are guaranteed to be visible to another. For example, unlocking a monitor happens-before every later lock of the same monitor, a volatile write happens-before every later read of that variable, and Thread.start happens-before the actions of the started thread. Without a happens-before edge, a thread may see stale or reordered values.
Interview Tips
- Always distinguish atomicity (one indivisible step) from visibility (other threads see the change).
- Describe a real concurrency bug you debugged; it shows you understand the topics beyond definitions.
- Know which tool you would pick for a problem: executor, atomic, concurrent collection, or lock.