Java Notes
35+ Java Multithreading interview questions covering threads, synchronization, locks, executor framework, concurrent collections, and thread communication.
1. What is a Thread? How to create threads in Java?
A thread is the smallest unit of execution. Two ways to create:
// Way 1: Extend Thread class
class MyThread extends Thread {
public void run() { System.out.println("Thread running: " + getName()); }
}
new MyThread().start();
// Way 2: Implement Runnable (preferred)
class MyTask implements Runnable {
public void run() { System.out.println("Task running"); }
}
new Thread(new MyTask()).start();
// Way 3: Lambda (Java 8+)
new Thread(() -> System.out.println("Lambda thread")).start();
// Way 4: Callable (returns result)
Callable<Integer> task = () -> { return 42; };
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<Integer> future = executor.submit(task);
int result = future.get(); // Blocks until done3. What is synchronization? Why is it needed?
Synchronization prevents multiple threads from accessing shared resources simultaneously (race condition):
4. synchronized method vs synchronized block?
// Synchronized method — locks entire object (this)
public synchronized void method() { /* ... */ }
// Synchronized block — locks specific object (fine-grained)
public void method() {
// Non-synchronized code here...
synchronized (this) {
// Only this part is locked
}
// Can also lock on specific object:
synchronized (sharedList) {
sharedList.add(item);
}
}Block is preferred — locks only what's needed, better performance.
5. What is a deadlock? How to prevent it?
Deadlock occurs when two threads hold locks and wait for each other:
// Thread 1: locks A, waits for B
synchronized(lockA) {
synchronized(lockB) { /* work */ }
}
// Thread 2: locks B, waits for A
synchronized(lockB) {
synchronized(lockA) { /* work */ }
}Prevention:
- Lock ordering — always acquire locks in same order
- Lock timeout — use
tryLock()with timeout - Avoid nested locks
- Use concurrent utilities instead of manual synchronization
6. wait(), notify(), notifyAll() — explain.
These are inter-thread communication methods (called inside synchronized block):
class SharedQueue {
private Queue<Integer> queue = new LinkedList<>();
private int capacity = 5;
public synchronized void produce(int item) throws InterruptedException {
while (queue.size() == capacity) {
wait(); // Release lock and wait
}
queue.add(item);
System.out.println("Produced: " + item);
notifyAll(); // Wake up waiting consumers
}
public synchronized int consume() throws InterruptedException {
while (queue.isEmpty()) {
wait(); // Release lock and wait
}
int item = queue.poll();
System.out.println("Consumed: " + item);
notifyAll(); // Wake up waiting producers
return item;
}
}7. sleep() vs wait()
| Feature | sleep() | wait() |
|---|---|---|
| Class | Thread | Object |
| Lock | Does NOT release | Releases lock |
| Wake up | After time expires | notify()/notifyAll() |
| Called in | Anywhere | synchronized block only |
| Purpose | Pause execution | Inter-thread communication |
8. What is volatile keyword?
Ensures visibility — all threads see the latest value:
private volatile boolean running = true;
// Thread 1
public void run() {
while (running) { /* work */ } // Always reads from main memory
}
// Thread 2
public void stop() {
running = false; // Immediately visible to Thread 1
}volatile provides visibility, NOT atomicity. For atomic operations, use AtomicInteger.
9. What is the Executor Framework?
// Fixed thread pool
ExecutorService executor = Executors.newFixedThreadPool(5);
// Submit tasks
executor.submit(() -> System.out.println("Task 1"));
executor.submit(() -> System.out.println("Task 2"));
// Submit with result
Future<String> future = executor.submit(() -> "Hello");
String result = future.get(); // Blocks until complete
// Shutdown
executor.shutdown();
executor.awaitTermination(60, TimeUnit.SECONDS);| Executor Type | Description |
|---|---|
newFixedThreadPool(n) | Fixed number of threads |
newCachedThreadPool() | Creates threads as needed, reuses |
newSingleThreadExecutor() | Single thread, tasks queued |
newScheduledThreadPool(n) | For scheduled/periodic tasks |
10. What is CompletableFuture?
CompletableFuture<String> future = CompletableFuture
.supplyAsync(() -> fetchFromDatabase()) // Async
.thenApply(data -> transform(data)) // Transform
.thenCompose(result -> saveAsync(result)) // Chain async
.exceptionally(ex -> "Error: " + ex.getMessage());
// Combine multiple futures
CompletableFuture<Void> all = CompletableFuture.allOf(future1, future2, future3);
CompletableFuture<Object> any = CompletableFuture.anyOf(future1, future2);11. What are Atomic classes?
AtomicInteger counter = new AtomicInteger(0);
counter.incrementAndGet(); // Thread-safe increment
counter.compareAndSet(5, 10); // CAS operation
counter.getAndAdd(5); // Get current, add 5Uses CPU-level CAS (Compare-And-Swap) — no locks needed.
12. What is ThreadLocal?
Provides thread-specific storage — each thread has its own copy:
private static ThreadLocal<SimpleDateFormat> dateFormatter =
ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyy-MM-dd"));
// Each thread gets its own SimpleDateFormat instance
String date = dateFormatter.get().format(new Date());13-35. Additional Questions
13. What is a daemon thread? Background thread (GC, signal handler). JVM exits when only daemon threads remain. Set via thread.setDaemon(true).
14. join() method? Makes calling thread wait until target thread finishes.
15. What is thread starvation? A thread never gets CPU time because higher-priority threads dominate.
16. What is livelock? Threads keep responding to each other without making progress (neither blocked nor making progress).
17. ReentrantLock vs synchronized?
- ReentrantLock: tryLock(), timeout, fairness, multiple conditions
- synchronized: simpler syntax, automatic unlock
18. What is ReadWriteLock? Multiple readers OR one writer. ReentrantReadWriteLock — improves read-heavy scenarios.
19. What is CountDownLatch? Allows threads to wait until a set of operations complete. Count down from N to 0.
20. What is CyclicBarrier? All threads wait at barrier until all arrive. Can be reused (cyclic).
21. What is Semaphore? Controls access to a resource with limited permits. acquire() and release().
22. What is a Fork/Join framework? Divide task into subtasks recursively, execute in parallel, join results. Uses work-stealing algorithm.
23. Thread priority? 1 (MIN) to 10 (MAX), default 5. Hint to scheduler, not guaranteed.
24. Can we restart a dead thread? No. Once TERMINATED, cannot be started again. Create a new thread.
25. What is thread-safe? Code that works correctly with multiple concurrent threads accessing shared state.
26. What is an immutable object? Object whose state cannot change — inherently thread-safe without synchronization.
27. What is a race condition? When program behavior depends on relative timing of threads.
28. What is the happens-before relationship? Guarantees that memory writes by one thread are visible to another.
29. What is false sharing? Multiple threads modify variables on the same cache line, causing unnecessary cache invalidation.
30. What is a Phaser? Flexible synchronization barrier for multiple phases. More advanced than CyclicBarrier/CountDownLatch.
31. BlockingQueue implementations? ArrayBlockingQueue (bounded), LinkedBlockingQueue (optionally bounded), PriorityBlockingQueue, SynchronousQueue.
32. What is a thread dump? Snapshot of all thread states. Get via jstack, kill -3, or Thread.dumpStack().
33. How to handle exceptions in threads? Thread.setUncaughtExceptionHandler() or catch within run().
34. What is StampedLock? Optimistic reading lock. Even faster than ReadWriteLock for read-heavy workloads.
35. Virtual threads (Java 21)? Lightweight threads (Project Loom). Millions of virtual threads possible. Thread.startVirtualThread(() -> task()).
13. What is a Thread Pool? How to use ExecutorService?
Answer: A Thread Pool is a collection of pre-created threads that execute tasks. Instead of creating a new thread for each task, threads are reused from the pool. The ExecutorService interface manages thread pools.
Task 0 - Thread: pool-1-thread-1 Task 1 - Thread: pool-1-thread-2 Task 2 - Thread: pool-1-thread-3 Task 3 - Thread: pool-1-thread-4 Task 4 - Thread: pool-1-thread-5 Task 5 - Thread: pool-1-thread-1
14. What does the volatile keyword do?
Answer: A volatile variable's value is always read/written from main memory (not CPU cache). It provides a visibility guarantee — one thread's changes are immediately visible to other threads. But it does not guarantee atomicity.
private volatile boolean running = true;
// Thread 1
public void stop() { running = false; } // Visible to Thread 2 immediately
// Thread 2
while (running) { /* work */ } // Always reads latest value15. How do wait(), notify(), notifyAll() work?
Answer: These are Object class methods that must be called inside a synchronized block. wait() puts the thread into a waiting state and releases the lock. notify() wakes up one waiting thread, notifyAll() wakes up all.
16. What is the difference between Callable and Runnable?
Answer:
| Feature | Runnable | Callable |
|---|---|---|
| Method | run() | call() |
| Return | void | Generic type |
| Exception | Cannot throw checked | Can throw checked |
| Result | No | Future<V> |
Callable<Integer> task = () -> {
Thread.sleep(1000);
return 42;
};
Future<Integer> future = executor.submit(task);
System.out.println("Result: " + future.get()); // Blocks until doneResult: 42
17. What is the difference between ReentrantLock and synchronized?
Answer: ReentrantLock: tryLock() (non-blocking), lockInterruptibly(), fairness policy, multiple conditions. synchronized: simpler syntax, auto-release, but less flexible. ReentrantLock is better for complex scenarios.
18. What is CountDownLatch?
Answer: Used to make one thread wait for multiple threads to complete. The waiting thread proceeds when the countdown reaches zero. One-time use — cannot be reset.
All tasks completed!
19. CyclicBarrier vs CountDownLatch?
Answer: CountDownLatch: one-time use, one thread waits for others. CyclicBarrier: reusable, multiple threads wait for each other (meet at the barrier), then all proceed together.
20. What is CompletableFuture?
Answer: Introduced in Java 8 — for asynchronous programming. Non-blocking, chainable operations, exception handling. An advanced version of Future that supports callbacks.
CompletableFuture<String> future = CompletableFuture
.supplyAsync(() -> "Hello")
.thenApply(s -> s + " World")
.thenApply(String::toUpperCase);
System.out.println(future.get());HELLO WORLD
21. How to create a Thread-safe Singleton?
Answer: Use double-checked locking with volatile, enum singleton (best), or static inner class (Bill Pugh) approach.
22. What is a Semaphore?
Answer: Controls access to limited resources. Maintains a count of permits. acquire() takes a permit (or waits), release() returns the permit. Example: DB connection pool limit.
23. What is ThreadLocal?
Answer: Maintains a separate variable copy for each thread. Thread-safe without synchronization. Common use: per-request context (user info, transaction), SimpleDateFormat (not thread-safe).
24. How do Atomic classes (AtomicInteger, etc.) work?
Answer: They use CAS (Compare-And-Swap) operation — lock-free thread safety. incrementAndGet(), compareAndSet() etc. Faster than synchronized for simple counters.
25. What is the Fork/Join Framework?
Answer: Splits large tasks into smaller subtasks and executes them in parallel. Uses work-stealing algorithm. Extend RecursiveTask (returns value) and RecursiveAction (void).
26. What is ReadWriteLock?
Answer: Multiple readers can read simultaneously (shared lock), but a writer takes exclusive access. Provides better performance than synchronized in read-heavy scenarios.
27. What is Thread starvation?
Answer: A low-priority thread never gets to execute because high-priority threads always occupy the CPU. Solution: fair locks, priority adjustment, proper thread pool configuration.
28. What is the Happens-before relationship?
Answer: A concept of the Java Memory Model — guarantees that one action's results will be visible to another action. Examples: synchronized block exit happens-before next entry, volatile write happens-before subsequent read.
29. What is Phaser?
Answer: An advanced version of CountDownLatch + CyclicBarrier. Supports dynamic party registration, multiple phases, and flexible advancement. Useful in complex synchronization scenarios.
30. What is BlockingQueue? Name its types.
Answer: A thread-safe queue where the producer waits when the queue is full, and the consumer waits when the queue is empty. Types: ArrayBlockingQueue (bounded), LinkedBlockingQueue (optionally bounded), PriorityBlockingQueue (priority-based), SynchronousQueue (zero capacity).
Summary
In this chapter, we learned about Multithreading Interview Questions in detail. Here are the key points:
- Basic introduction to the concept and why it is needed
- Syntax and structure with complete examples
- Internal working and best practices
- Real-world applications and use cases
- Common mistakes and how to avoid them
- How this topic is asked in interviews
To practice these concepts, write and run the code in your IDE and verify the output. Modify each example and experiment so that you deeply understand the concept.
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Multithreading Interview Questions.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Java Master Course topic.
Search Terms
java-master-course, java master course, java, master, course, interview, questions, multithreading
Related Java Master Course Topics