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.
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 onet.join(); // wait for it to finish// Java 21: virtual threads, cheap enough to run millionsThread.startVirtualThread(task);
| State | Meaning |
|---|---|
| NEW | Created, not started |
| RUNNABLE | Running or ready to run |
| BLOCKED | Waiting for a monitor lock |
| WAITING / TIMED_WAITING | In wait(), join(), sleep(), park() |
| TERMINATED | Finished |
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.
class Counter {private int count;public synchronized void increment() { count++; } // one thread at a time per objectpublic synchronized int get() { return count; }}// Or lock-free:AtomicInteger hits = new AtomicInteger();hits.incrementAndGet(); // atomic compare-and-swap
synchronizedmethods lockthis(static ones lock theClass); asynchronized (obj)block locksobj.- 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.
class Worker implements Runnable {private volatile boolean running = true; // stop flag seen immediatelypublic 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.
ExecutorService pool = Executors.newFixedThreadPool(4);Future<Integer> f = pool.submit(() -> expensiveCount());int n = f.get(); // blocks until donepool.shutdown();CompletableFuture<String> page = CompletableFuture.supplyAsync(() -> fetch(url)) // runs on a pool.thenApply(String::toUpperCase) // transform when ready.exceptionally(e -> "fallback"); // recover from errorsString 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
ThreadPoolExecutordirectly 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.
BlockingQueue<Job> queue = new ArrayBlockingQueue<>(100); // bounded buffer// producerqueue.put(job); // blocks when full// consumerJob 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
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
0 of 4 answered