•Lucas Lyu
Java Interview Survival Guide: Concurrency & JVM Deep Dive
As I prepare for graduate roles, I'm organizing my notes on the "Hard Parts" of Java. These are the concepts that separate a "API User" from an "Engineer".
Note: This page is a living document. I will add more edge cases as I encounter them.
🧵 Part 1: Concurrency (JUC)
1. volatile vs synchronized
volatile: Guarantees visibility and prevents instruction reordering (Happens-Before relationship). It does not guarantee atomicity (e.g.,i++is not safe).synchronized: Guarantees visibility + atomicity. It's a pessimistic lock.
2. The AQS (AbstractQueuedSynchronizer) Framework
This is the heart of ReentrantLock, CountDownLatch, and Semaphore.
- Core Logic: Uses an
int statevariable (volatile) to represent lock status. - Queue: If a thread fails to acquire the lock, it's wrapped in a Node and added to a CLH (Craig, Landin, and Hagersten) variant queue (doubly linked list).
- CAS: State changes are protected by CAS (Compare-And-Swap) operations.
3. ThreadPoolExecutor Parameters
Never use Executors.newFixedThreadPool() in production (OOM risk). Always use ThreadPoolExecutor.
public ThreadPoolExecutor(
int corePoolSize, // Threads always alive
int maximumPoolSize, // Max threads (if queue is full)
long keepAliveTime, // Time for extra threads to die
TimeUnit unit,
BlockingQueue<Runnable> workQueue, // The buffer
ThreadFactory threadFactory, // Custom names/priorities
RejectedExecutionHandler handler // What to do when full (Abort, CallerRuns, etc.)
)
Key Question: What happens when a task is submitted?
- If
running < core, start new thread. - Else, put in
queue. - If
queuefull andrunning < max, start new thread. - If
queuefull andrunning == max, reject policy.
🚜 Part 2: JVM & GC
1. The Heap Structure (G1 / HotSpot)
- Young Gen: Eden + Survivor (S0, S1). Objects start here.
- Old Gen: Long-lived objects.
- Metaspace: Class metadata (Native Memory), replaced PermGen in Java 8.
2. GC Algorithms
- Mark-Sweep: Fragments memory.
- Mark-Compact: Solves fragmentation but slower (Stop-The-World).
- Copying: Great for Young Gen (Eden -> Survivor), wastes half space if not optimized.
3. CMS vs G1 vs ZGC
- CMS: Low latency, but fragmentation issues. Deprecated.
- G1 (Garbage First): Splits heap into Regions. Prioritizes regions with most garbage. Predictable pause times. Default in Java 9+.
- ZGC: Sub-millisecond pauses. Scalable to Terabytes.
📚 Recommended Reading
- Java Concurrency in Practice (The Bible)
- The Art of Multiprocessor Programming (For the brave)