1. The Exception Hierarchy
Throwable
├── Error (OOM, StackOverflow, linkage — do NOT catch)
└── Exception
├── RuntimeException (unchecked)
│ ├── NullPointerException
│ ├── ArrayIndexOutOfBoundsException
│ ├── ArithmeticException
│ ├── IllegalArgument/IllegalStateException
│ └── ClassCastException
└── (checked) IOException, SQLException, ...
- Checked: compiler forces catch-or-declare.
RuntimeExceptionand everything under it is unchecked. finallyalways runs (unlessSystem.exitor VM death).returninfinallyoverrides any try/catch return.- Multi-catch:
catch (IOException | SQLException e)— subclasses cannot share a multi-catch. catch (Exception e)is too broad in production — catch specific exceptions.
try (BufferedReader br = new BufferedReader(new FileReader(path))) {
return br.readLine();
} catch (IOException e) {
throw new RuntimeException("read failed", e);
}
try-with-resources
- Introduced Java 7 — closes any
AutoCloseableautomatically (in reverse-open order). - Resources declared in
try (...)are closed even on exception/return. - Catch block covers the whole operation;
suppressedexceptions available viae.getSuppressed().
Gotcha: if the primary operation throws and close also throws, close’s exception is suppressed (attached to the primary), not its own stack.
2. Threads & Runnable/Callable
- Thread via
extends Threadorimplements Runnable(prefer Runnable). start()launches a new thread;run()invoked synchronously in the current thread — a classic output trap (t.run()does not start a thread).- Callable returns a value + can throw; represented by Future.
Thread.currentThread(),getName(),setPriority(hint only),join()waits,sleep()pauses (can throw checkedInterruptedException).
ExecutorService ex = Executors.newFixedThreadPool(4);
Future<Integer> f = ex.submit(() -> expensive());
int result = f.get(); // blocks until done
ex.shutdown();
Two ways to start a thread
new Thread(new RunnableTask()).start()ExecutorService(preferred — decouples task from thread)
3. Synchronization & volatile
synchronizedmethod/block — monitor lock. Gives mutual exclusion + memory visibility.volatile— guarantees visibility of a single field across threads, but not atomicity.volatile counter++is NOT thread-safe (it’s a read-modify-write).- Atomic classes (
AtomicInteger,AtomicBoolean) give thread-safe increments (getAndIncrement());AtomicReference. - Latches/CyclicBarrier —
CountDownLatchfor one-shot waits;CyclicBarrierreusable. Semaphore— controls permit counts.
Gotcha: deadlock = two threads holding locks the other needs; fix by acquiring locks in a consistent global order.
4. Lock Stripping: synchronized vs ReentrantLock vs ConcurrentHashMap
| Utility | Key property |
|---|---|
synchronized | built-in; auto release; no timeouts/interrupt |
ReentrantLock | explicit lock()/unlock(); tryLock(timeout); fairness; reentrant (same thread can re-acquire) |
ConcurrentHashMap | lock-striped (segment or CAS), weak-consistency iteration |
CopyOnWriteArrayList | snapshot iteration — excellent for read-heavy |
BlockingQueue | thread-safe producer-consumer queues (LinkedBlockingQueue, ArrayBlockingQueue) |
5. Garbage Collection (the JVM interview segment)
- Generational: young (Eden + Survivor S0/S1) → old. Objects promoted after surviving enough minor GCs.
- Algorithms: Serial, Parallel, CMS (legacy), G1 (default; regional), ZGC (low-latency, large heaps).
- Stop-the-world pauses are minimized; CMS deprecated Java 9, but still ask about algorithms conceptually.
- Memory leaks (still possible): static collections that grow, unclosed resources, listeners registered but never unsubscribed (inner-class outer ref), naive caching.
- JVM flags:
-Xmx(max heap),-Xms(initial),-XX:+UseG1GC,-Xlog:gc.
Interview checkpoint: name the cycle: new → young gen → promoted → old gen → Full GC pause → arguably major red flag if the collection frequently grows.
6. The key synchronized facts
- A
synchronizedinstance method locksthis; a static method locks the Class object. - Locks are reentrant — a synchronized method calling another synchronized method on the same object doesn’t deadlock itself.
synchronizedblocks use a monitor per object; thread-safe collections hide their own synchronisation.
Top-3 concurrency questions: (1) difference volatile vs synchronized/Atomic; (2) how to avoid deadlock (lock ordering + tryLock); (3) when HashMap becomes unsafe and what ConcurrentHashMap does instead.
Premium Content
Unlock Part 5: Exceptions, Concurrency & JVM and all premium lessons with a subscription.
All premium lessons
Ad-free experience
Priority support
From ₹199.99/year — See plans