Menu

Earn Premium with Referrals

Invite your friends and earn Premium rewards through our referral program.

See how it works and start inviting friends.

Part 5: Exceptions, Concurrency & JVM
JAVA

Part 5: Exceptions, Concurrency & JVM

Revise Java exception handling, try-with-resources, threads, locks, synchronization, and garbage collection.

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. RuntimeException and everything under it is unchecked.
  • finally always runs (unless System.exit or VM death). return in finally overrides 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 AutoCloseable automatically (in reverse-open order).
  • Resources declared in try (...) are closed even on exception/return.
  • Catch block covers the whole operation; suppressed exceptions available via e.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 Thread or implements 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 checked InterruptedException).
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

  1. new Thread(new RunnableTask()).start()
  2. ExecutorService (preferred — decouples task from thread)

3. Synchronization & volatile

  • synchronized method/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/CyclicBarrierCountDownLatch for one-shot waits; CyclicBarrier reusable.
  • 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

UtilityKey property
synchronizedbuilt-in; auto release; no timeouts/interrupt
ReentrantLockexplicit lock()/unlock(); tryLock(timeout); fairness; reentrant (same thread can re-acquire)
ConcurrentHashMaplock-striped (segment or CAS), weak-consistency iteration
CopyOnWriteArrayListsnapshot iteration — excellent for read-heavy
BlockingQueuethread-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 synchronized instance method locks this; 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.
  • synchronized blocks 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.

My Private Notes

Notes are auto-saved locally to this device.