Brainbotox · Lessons · Exams

Advanced Java: JVM Internals, Memory, Concurrency, Performance

by lazizanie · Programming · Java · English

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

PhaseWhat happens
LoadingThe class file is found and read into the JVM
LinkingVerification of bytecode, preparation of static fields with default values, resolution of symbolic references
InitializationStatic 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.

A class is identified by its fully qualified name and its class loader. The same class file loaded by two loaders gives two incompatible types, the classic cause of a confusing ClassCastException in application servers.

Run-time data areas

AreaScopeHolds
HeapSharedAll objects and arrays; managed by the GC
JVM stackPer threadFrames: local variables, operand stack. Overflow gives StackOverflowError
MetaspaceShared, native memoryClass metadata (replaced PermGen in Java 8)
Code cacheSharedMachine code produced by the JIT

Execution: interpreter and tiered JIT

  1. Bytecode starts in the interpreter.
  2. Methods that run often are compiled by C1, a fast compiler that also gathers profiling data.
  3. 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.

This is why Java code is slow at start-up and speeds up as it warms. Benchmarks must include a warm-up phase.

Check yourself

  1. What is the parent delegation model?
  2. When do a class's static initialisers run?
  3. Where is class metadata stored since Java 8?
  4. Which memory area is private to each thread?
  5. What is the role of C2 in tiered compilation?
  6. What is deoptimisation?

Take the quiz on Brainbotox

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

RegionContainsCollection
Young: Eden and two survivor spacesNew objectsMinor GC: frequent, fast, copies survivors
OldObjects that survived several minor GCsRarer and more expensive

The collectors

CollectorGoalNotes
SerialSmall heaps, one CPUSingle-threaded, stop-the-world
ParallelMaximum throughputLonger pauses; batch jobs
G1Balance of throughput and pause timeDefault since Java 9; heap split into regions; pause target with -XX:MaxGCPauseMillis
ZGC, ShenandoahVery low pauses on large heapsConcurrent marking and compaction; pauses do not grow with heap size

Reference types

ReferenceClearedUse
StrongNever while reachableNormal references
SoftReferenceWhen memory is low, before OutOfMemoryErrorMemory-sensitive caches
WeakReferenceAt the next GC once no strong reference remainsWeakHashMap, listeners
PhantomReferenceAfter the object is finalisedClean-up actions (Cleaner)

Memory leaks in Java

A leak is an object that is still reachable but no longer needed. Usual causes: static collections that only grow, caches without eviction, listeners never removed, ThreadLocal values in pooled threads, and unclosed resources.

Diagnosis and tuning

  • -Xms and -Xmx set the initial and maximum heap. In containers prefer -XX:MaxRAMPercentage.
  • -Xlog:gc* writes GC logs.
  • -XX:+HeapDumpOnOutOfMemoryError produces a heap dump to analyse with Eclipse MAT or VisualVM.
  • OutOfMemoryError: Java heap space points to the heap; Metaspace points 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

  1. Which collector has been the JVM default since Java 9?
  2. Which of these is a GC root?
  3. When is a SoftReference cleared?
  4. What is the main strength of ZGC?
  5. What is a memory leak in a garbage-collected language?
  6. Which flag sets the maximum heap size?

Take the quiz on Brainbotox

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 volatile field happens-before every later read of it.
  • Thread.start() happens-before the first action of the started thread; the end of a thread happens-before join() returns.
  • Writes to final fields in a constructor are visible to any thread that obtains the object after construction, provided this did 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

volatilesynchronized
VisibilityYesYes
Atomic compound actions (x++)NoYes
Blocks threadsNoYes

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;
}
Simpler and safe: the initialization-on-demand holder idiom (a static nested class holding the instance) or a single-element 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

LockAdds over synchronized
ReentrantLocktryLock, timeouts, interruptible waits, fairness, several Conditions
ReentrantReadWriteLockMany readers or one writer
StampedLockOptimistic reads that take no lock
Always release an explicit lock in finally. Both synchronized and ReentrantLock are reentrant: a thread can re-acquire a lock it already holds.

Check yourself

  1. What does the happens-before relation guarantee?
  2. Why can while (running) { } never end when running is not volatile?
  3. Why must the field be volatile in double-checked locking?
  4. What does compareAndSet(expected, update) do?
  5. What is the ABA problem?
  6. What does ReentrantLock offer that synchronized does not?

Take the quiz on Brainbotox

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());
Order of decisions for a new task: use a core thread if one is free to be created; otherwise queue it; only when the queue is full create threads up to the maximum; then apply the rejection policy. With an unbounded queue, the maximum is never reached.
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

MethodUse
thenApplyTransform the result (like map)
thenComposeChain another async call (like flatMap)
thenCombineMerge two independent futures
allOf, anyOfWait for all, or the first
exceptionally, handleRecover 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 synchronized also pinned; JDK 24 removed that limitation.
  • ThreadLocal works but is costly with millions of threads; scoped values are the intended replacement.

Check yourself

  1. In ThreadPoolExecutor, when are threads beyond corePoolSize created?
  2. What is the risk of an unbounded work queue?
  3. Which method chains a second asynchronous call without nesting futures?
  4. Virtual threads should be pooled like platform threads.
  5. What happens when a virtual thread blocks on socket I/O?
  6. Which pool runs parallel streams by default?

Take the quiz on Brainbotox

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
}
JMH handles warm-up, forks fresh JVMs, and prevents dead code elimination when you return the value or pass it to a Blackhole.

Profiling and diagnostic tools

ToolUse
Java Flight Recorder (JFR)Low-overhead recording of CPU, allocation, locks and GC; safe in production
async-profilerCPU and allocation flame graphs without safepoint bias
jcmd, jstackThread dumps: find deadlocks and blocked threads
jmap, heap dumpsWhat fills the heap
GC logsPause 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> and Stream<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.
Method: set a measurable goal, profile under realistic load, fix the largest hot spot, measure again. The bottleneck is usually an algorithm, a query or I/O, not a micro-optimisation.

Check yourself

  1. Why are hand-written timing loops unreliable in Java?
  2. Which tool is the standard for Java microbenchmarks?
  3. In JMH, why should a benchmark method return its result?
  4. What is Java Flight Recorder?
  5. What can escape analysis allow the JIT to do?
  6. Which tool shows the stack of every thread to diagnose a deadlock?

Take the quiz on Brainbotox

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);
Reflection loses compile-time checking, is slower than direct calls, and breaks encapsulation. Since Java 17 the JDK's internals are strongly encapsulated: deep reflection into them fails unless the package is opened.

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

RetentionAvailableExample use
SOURCETo the compiler only@Override
CLASSIn the class file, not at run time (the default)Bytecode tools
RUNTIMEThrough 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

GainCost
Starts in milliseconds, low memoryLong build times
No JVM neededClosed-world assumption: all code must be known at build time
Good for serverless and CLIsReflection, proxies and resources must be declared; peak throughput can be lower than a warmed-up JIT

Check yourself

  1. What can java.lang.reflect.Proxy create a proxy for?
  2. Which retention makes an annotation readable through reflection?
  3. When does an annotation processor run?
  4. How are lambdas compiled?
  5. In module-info.java, what does opens add compared with exports?
  6. What is the closed-world assumption of GraalVM native image?

Take the quiz on Brainbotox