Advanced Java: JVM Internals, Memory, Concurrency, Performance
Advanced Java for senior developers: class loading and JIT, garbage collectors, the Java Memory Model, executors and virtual threads, profiling with JMH and JFR, reflection and modules.
Study this lesson with its quizzes on Brainbotox →
JVM architecture: class loading, memory areas and JIT
The JVM loads classes on demand through a hierarchy of class loaders, stores data in a few well-defined memory areas, and runs bytecode with an interpreter backed by a tiered just-in-time compiler.
Class loading
| Phase | What happens |
|---|---|
| Loading | The class file is found and read into the JVM |
| Linking | Verification of bytecode, preparation of static fields with default values, resolution of symbolic references |
| Initialization | Static initialisers and static field assignments run, once, on first active use |
Class loaders and parent delegation
The three built-in loaders are bootstrap (core JDK classes), platform and application (the classpath). A loader first asks its parent, and loads the class itself only if the parent cannot. This prevents application code from replacing java.lang.String.
ClassCastException in application servers.Run-time data areas
| Area | Scope | Holds |
|---|---|---|
| Heap | Shared | All objects and arrays; managed by the GC |
| JVM stack | Per thread | Frames: local variables, operand stack. Overflow gives StackOverflowError |
| Metaspace | Shared, native memory | Class metadata (replaced PermGen in Java 8) |
| Code cache | Shared | Machine code produced by the JIT |
Execution: interpreter and tiered JIT
- Bytecode starts in the interpreter.
- Methods that run often are compiled by C1, a fast compiler that also gathers profiling data.
- The hottest methods are recompiled by C2 with aggressive, profile-guided optimisations: inlining, escape analysis, loop unrolling.
C2 makes optimistic assumptions (for example "this interface has one implementation"). If one becomes false, the JVM deoptimises the method back to the interpreter.
Check yourself
- What is the parent delegation model?
- When do a class's static initialisers run?
- Where is class metadata stored since Java 8?
- Which memory area is private to each thread?
- What is the role of C2 in tiered compilation?
- What is deoptimisation?
Java garbage collection: G1, ZGC, references and memory leaks
The JVM garbage collector reclaims objects that are no longer reachable from GC roots, and most collectors are generational because most objects die young.
Reachability
GC roots are local variables on thread stacks, static fields, and JNI references. An object reachable from a root is alive. Everything else is garbage, including cycles.
Generations
| Region | Contains | Collection |
|---|---|---|
| Young: Eden and two survivor spaces | New objects | Minor GC: frequent, fast, copies survivors |
| Old | Objects that survived several minor GCs | Rarer and more expensive |
The collectors
| Collector | Goal | Notes |
|---|---|---|
| Serial | Small heaps, one CPU | Single-threaded, stop-the-world |
| Parallel | Maximum throughput | Longer pauses; batch jobs |
| G1 | Balance of throughput and pause time | Default since Java 9; heap split into regions; pause target with -XX:MaxGCPauseMillis |
| ZGC, Shenandoah | Very low pauses on large heaps | Concurrent marking and compaction; pauses do not grow with heap size |
Reference types
| Reference | Cleared | Use |
|---|---|---|
| Strong | Never while reachable | Normal references |
SoftReference | When memory is low, before OutOfMemoryError | Memory-sensitive caches |
WeakReference | At the next GC once no strong reference remains | WeakHashMap, listeners |
PhantomReference | After the object is finalised | Clean-up actions (Cleaner) |
Memory leaks in Java
ThreadLocal values in pooled threads, and unclosed resources.Diagnosis and tuning
-Xmsand-Xmxset the initial and maximum heap. In containers prefer-XX:MaxRAMPercentage.-Xlog:gc*writes GC logs.-XX:+HeapDumpOnOutOfMemoryErrorproduces a heap dump to analyse with Eclipse MAT or VisualVM.OutOfMemoryError: Java heap spacepoints to the heap;Metaspacepoints to too many loaded classes, often a class loader leak.
finalize() is deprecated. Use try-with-resources, or Cleaner as a last resort.Check yourself
- Which collector has been the JVM default since Java 9?
- Which of these is a GC root?
- When is a SoftReference cleared?
- What is the main strength of ZGC?
- What is a memory leak in a garbage-collected language?
- Which flag sets the maximum heap size?
The Java Memory Model, volatile, CAS and locks
The Java Memory Model (JMM) defines when a write made by one thread is guaranteed to be visible to another, through the happens-before relation. Without such a relation, a thread may see a stale value forever.
Happens-before
If action A happens-before action B, then B sees the effects of A. The main rules:
- An unlock of a monitor happens-before every later lock of that monitor.
- A write to a
volatilefield happens-before every later read of it. Thread.start()happens-before the first action of the started thread; the end of a thread happens-beforejoin()returns.- Writes to
finalfields in a constructor are visible to any thread that obtains the object after construction, providedthisdid not escape.
boolean running = true; // not volatile
void loop() { while (running) { } } // may never stop: the JIT can hoist the read
void stop() { running = false; }volatile versus synchronized
| volatile | synchronized | |
|---|---|---|
| Visibility | Yes | Yes |
Atomic compound actions (x++) | No | Yes |
| Blocks threads | No | Yes |
Double-checked locking
private static volatile Config instance; // volatile is required
static Config get() {
Config c = instance;
if (c == null) {
synchronized (Config.class) {
c = instance;
if (c == null) instance = c = new Config();
}
}
return c;
}enum.Compare-and-swap
AtomicInteger n = new AtomicInteger();
int old;
do { old = n.get(); } while (!n.compareAndSet(old, old + 1));CAS updates a value only if it still equals the expected one, with no lock. The ABA problem (value changed from A to B and back) is solved with AtomicStampedReference. Under heavy contention, LongAdder scales better than AtomicLong.
Explicit locks
| Lock | Adds over synchronized |
|---|---|
ReentrantLock | tryLock, timeouts, interruptible waits, fairness, several Conditions |
ReentrantReadWriteLock | Many readers or one writer |
StampedLock | Optimistic reads that take no lock |
finally. Both synchronized and ReentrantLock are reentrant: a thread can re-acquire a lock it already holds.Check yourself
- What does the happens-before relation guarantee?
- Why can while (running) { } never end when running is not volatile?
- Why must the field be volatile in double-checked locking?
- What does compareAndSet(expected, update) do?
- What is the ABA problem?
- What does ReentrantLock offer that synchronized does not?
Java executors, CompletableFuture and virtual threads in depth
Scalable Java services depend on correctly sized thread pools, non-blocking composition with CompletableFuture, and, since Java 21, virtual threads that make blocking code cheap.
ThreadPoolExecutor
new ThreadPoolExecutor(
4, // corePoolSize
16, // maximumPoolSize
60, TimeUnit.SECONDS, // keep-alive of extra threads
new ArrayBlockingQueue<>(100),
new ThreadPoolExecutor.CallerRunsPolicy());Executors.newFixedThreadPool uses an unbounded queue and newCachedThreadPool an unbounded number of threads. Under overload both can exhaust memory. Prefer bounded queues.Sizing: CPU-bound work needs about one thread per core. Blocking I/O work needs more, roughly cores multiplied by (1 + wait time / compute time).
ForkJoinPool
A work-stealing pool for tasks that split into subtasks. The common pool runs parallel streams and, by default, CompletableFuture async stages. Blocking inside it starves everything else that uses it.
CompletableFuture composition
| Method | Use |
|---|---|
thenApply | Transform the result (like map) |
thenCompose | Chain another async call (like flatMap) |
thenCombine | Merge two independent futures |
allOf, anyOf | Wait for all, or the first |
exceptionally, handle | Recover from failure |
...Async(fn, executor) | Run the stage on a chosen executor |
Synchronisers
CountDownLatch waits for N events once. CyclicBarrier makes N threads meet repeatedly. Semaphore limits concurrent access to N permits.
Virtual threads
- A virtual thread is scheduled by the JVM onto a small pool of platform carrier threads.
- When it blocks on I/O or a lock from
java.util.concurrent, it unmounts and the carrier runs another virtual thread. - They are cheap: create one per task and never pool them. Limit access to a scarce resource with a
Semaphore. - They do not speed up CPU-bound code.
- Pinning: a virtual thread that cannot unmount holds its carrier. Native calls pin. In older releases blocking inside
synchronizedalso pinned; JDK 24 removed that limitation. ThreadLocalworks but is costly with millions of threads; scoped values are the intended replacement.
Check yourself
- In ThreadPoolExecutor, when are threads beyond corePoolSize created?
- What is the risk of an unbounded work queue?
- Which method chains a second asynchronous call without nesting futures?
- Virtual threads should be pooled like platform threads.
- What happens when a virtual thread blocks on socket I/O?
- Which pool runs parallel streams by default?
Java performance tuning and profiling: JMH, JFR and JIT
Reliable Java performance work means measuring with the right tool, because the JIT compiler makes naive timing loops misleading.
Why System.nanoTime loops lie
- Warm-up: early iterations run interpreted, later ones compiled.
- Dead code elimination: if a result is unused, the JIT removes the computation.
- Constant folding: inputs known at compile time are precomputed.
- GC pauses and other processes add noise.
JMH
@State(Scope.Thread)
@BenchmarkMode(Mode.AverageTime)
@Warmup(iterations = 5)
@Measurement(iterations = 10)
@Fork(2)
public class JoinBench {
List<String> parts; // state: not a constant
@Setup public void init() { parts = List.of("a", "b", "c"); }
@Benchmark
public String join() { return String.join(",", parts); } // return the result
}Blackhole.Profiling and diagnostic tools
| Tool | Use |
|---|---|
| Java Flight Recorder (JFR) | Low-overhead recording of CPU, allocation, locks and GC; safe in production |
| async-profiler | CPU and allocation flame graphs without safepoint bias |
jcmd, jstack | Thread dumps: find deadlocks and blocked threads |
jmap, heap dumps | What fills the heap |
| GC logs | Pause times and allocation rate |
What the JIT does for you
- Inlining of small and hot methods, the gateway to other optimisations.
- Escape analysis: an object that never leaves a method can be replaced by its fields (scalar replacement), so no allocation happens, and locks on it are removed.
Frequent causes of slow code
- Autoboxing:
Map<Integer, Long>andStream<Integer>allocate wrappers; use primitive streams or arrays. - Exceptions used for control flow: filling the stack trace is expensive.
- Collections created without an initial capacity, then resized repeatedly.
- Lock contention; holding locks during I/O.
- False sharing: fields written by different threads on one cache line.
- Reflection in hot paths.
Check yourself
- Why are hand-written timing loops unreliable in Java?
- Which tool is the standard for Java microbenchmarks?
- In JMH, why should a benchmark method return its result?
- What is Java Flight Recorder?
- What can escape analysis allow the JIT to do?
- Which tool shows the stack of every thread to diagnose a deadlock?
Java reflection, annotations, modules and native images
Java frameworks such as Spring and Hibernate are built on metaprogramming: reflection, dynamic proxies, annotations and bytecode generation. The module system and native images constrain how far those techniques can go.
Reflection
Class<?> type = Class.forName("com.acme.User");
Object user = type.getDeclaredConstructor().newInstance();
Field f = type.getDeclaredField("name");
f.setAccessible(true); // bypass private, if the module allows
f.set(user, "Ada");
Method m = type.getMethod("getName");
Object value = m.invoke(user);Dynamic proxies
Service proxy = (Service) Proxy.newProxyInstance(
Service.class.getClassLoader(),
new Class<?>[] { Service.class },
(p, method, args) -> {
log(method.getName());
return method.invoke(target, args);
});java.lang.reflect.Proxy creates, at run time, an object that implements given interfaces and routes every call to a handler. Transactions, security and lazy loading are implemented this way. To proxy a class, frameworks generate a subclass with a bytecode library.
Annotations
| Retention | Available | Example use |
|---|---|---|
SOURCE | To the compiler only | @Override |
CLASS | In the class file, not at run time (the default) | Bytecode tools |
RUNTIME | Through reflection | @Test, dependency injection |
Annotation processors run inside javac and generate new source files at compile time: MapStruct, Dagger. No run-time cost and errors appear at build time.
invokedynamic and method handles
Lambdas are not compiled to anonymous inner classes. The compiler emits an invokedynamic instruction, and the implementation is linked at first use. MethodHandle is a typed, JIT-friendly reference to a method, faster than Method.invoke.
The module system (JPMS)
module com.acme.orders {
requires java.sql;
exports com.acme.orders.api; // public API
opens com.acme.orders.model; // allow deep reflection
}exports gives compile-time and run-time access to public types. opens additionally permits reflection on private members.
GraalVM native image
| Gain | Cost |
|---|---|
| Starts in milliseconds, low memory | Long build times |
| No JVM needed | Closed-world assumption: all code must be known at build time |
| Good for serverless and CLIs | Reflection, proxies and resources must be declared; peak throughput can be lower than a warmed-up JIT |
Check yourself
- What can java.lang.reflect.Proxy create a proxy for?
- Which retention makes an annotation readable through reflection?
- When does an annotation processor run?
- How are lambdas compiled?
- In module-info.java, what does opens add compared with exports?
- What is the closed-world assumption of GraalVM native image?