← All topics

JVM and memory

Heap, stack, the garbage collector and memory problems.

200 questions

Start ▶
Level:
1 How do the JDK, JRE and JVM differ from each other? The JVM is the virtual machine that executes bytecode. The JRE is the JVM plus the standard libraries, enough to run a program. The JDK is the JRE plus developer tools like javac, jar and jcmd. Junior 2 What is bytecode, and what is actually inside a .class file? Bytecode is the set of platform-independent intermediate instructions that javac produces. A .class file holds those instructions, the constant pool, fields, methods and other metadata. Junior 3 How does the "Write Once, Run Anywhere" (WORA) idea work technically in Java? The code is compiled to platform-independent bytecode, and each OS and processor has its own JVM. The same .class file runs on Linux and on Windows, on that platform's JVM. Junior 4 Explain the difference between heap and stack memory. Stack / Heap — Who owns it: each thread has its own / shared by all threads; What it stores: frames: local variables, parameters, return address / objects, arrays; Who cleans it: the frame disappears when the method ends / the garbage collector; Size: small (-Xss, usually 512KB-1MB) / large (-Xmx); Error… Junior 5 What is inside a stack frame when a method is called? Each call opens a new frame: it holds an array of local variables, an operand stack and a reference to the constant pool. When the method returns, the frame is removed entirely. Junior 6 When does a StackOverflowError appear, and how do you track it down? When a thread's stack fills up, usually in recursion that never ends or goes very deep. In the stack trace the same methods repeat over and over, and the repeating part points to the cause. Junior 7 What does the garbage collector do, and what would happen without it? The GC finds objects on the heap that nobody uses anymore and frees the memory they occupy. Without it you would have to free memory by hand as in C, and bugs like leaks and double frees would multiply. Junior 8 When does an object become eligible for garbage collection? When it can no longer be reached from the GC roots through any chain of strong references. It doesn't matter that the object itself holds references to other objects; what matters is whether there is a path to it from something alive. Junior 9 What does the JVM do when you call System.gc() from code? It is only a request to the JVM that "you may run a GC", not a guarantee. On HotSpot it usually triggers a full GC, which can slow the application down, so it is almost never used in production code. Junior 10 What is Metaspace, and why did it replace PermGen in Java 8? Metaspace is the native memory area where class metadata (class structure, methods, bytecode) is stored. PermGen was a fixed-size area inside the heap and often filled up; Metaspace grows by default. Junior 11 What do the -Xms and -Xmx parameters set? -Xms is the initial heap size when the JVM starts, and -Xmx is the maximum size the heap can grow to. For example, -Xms512m -Xmx2g. Junior 12 What does the -Xss flag configure, and when do you have to change it? -Xss sets the size of each thread's stack. You can raise it for deep recursion, or lower it to save memory when there are very many threads. Junior 13 What does it mean when you see "OutOfMemoryError: Java heap space" in the log? The JVM couldn't find room on the heap for a new object, and the GC couldn't free enough space either. The cause is either a heap that is too small, a memory leak, or too much data being loaded at once. Junior 14 What is a ClassLoader, and what does it do? A ClassLoader is the component that finds .class files (on disk, in a jar, over the network) and turns them into Class objects inside the JVM. Each class is identified together with the loader that loaded it. Junior 15 What is the hierarchy of the standard ClassLoaders in Java, and how does "parent delegation" work? There are three main loaders: Bootstrap, Platform (Extension in Java 8) and Application. When a class is requested, a loader first asks its parent and loads it itself only if the parent can't find it. Junior 16 Exactly when is a class loaded and initialized by the JVM? A class is loaded lazily, the first time it is needed. Initialization happens on the first active use: creating an object, calling a static method, reading a non-constant static field, or when a subclass is initialized. Junior 17 When and how many times is a static block in a class executed? A static block runs once, during class initialization, that is, on the first active use of the class. If there are several static blocks, they run in the order they appear in the code. Junior 18 What is the JIT compiler, and why does it make Java faster? JIT (Just-In-Time) is the part of the JVM that compiles frequently executed bytecode into native machine code while the program is running. After that, that code runs directly on the processor with no interpretation. Junior 19 What is the difference between an interpreter and JIT compilation, and why does the JVM use both? The interpreter runs bytecode right away but slowly; the JIT spends time on compilation, but afterward the code runs much faster. The JVM interprets rarely used code and compiles only the hot code. Junior 20 What is the purpose of splitting the heap into young and old generations? It is based on the observation that most objects "die" very quickly. New objects are born in the young generation and are cleaned often and cheaply; the long-lived ones are moved to the old generation and checked less often. Junior 21 How do you tell apart the terms Minor GC, Major GC and Full GC? A Minor GC cleans only the young generation and is usually short. A Major GC deals with the old generation. A Full GC cleans the whole heap (often Metaspace too) and gives the longest pause. Junior 22 What do you understand by a stop-the-world pause? The time during which the JVM stops all application threads in order to do part of the GC's work. During this time requests don't get answered, so the length of the pause directly affects latency. Junior 23 Since there is a garbage collector, can a Java application still have a memory leak? Yes. The GC collects only unreachable objects. If an object is no longer needed but some static collection, cache or listener still holds a reference to it, it is never cleaned. Junior 24 What was the finalize() method meant for, and why shouldn't you use it? finalize() was a "cleanup" method that was supposed to be called before the GC collected an object. There is no guarantee when it is called, it slows the GC down, and it has been deprecated since Java 9 and marked for removal since Java 18. Junior 25 In which part of JVM memory is the string pool, where string literals are stored? Since Java 7 the string pool is inside the heap. Before that it was in PermGen, which could fill up; now the strings in the pool can be cleaned by the GC like ordinary objects. Junior 26 In the following method, which values are stored on the stack and which on the heap? price and qty are on the stack as primitive local variables. The name and order references are also on the stack, but the String and Order objects they point to are on the heap; the fields inside Order are on the heap with the object. Junior 27 What is a heap dump, and how can you take one? A heap dump is a snapshot of the entire heap at a given moment: all objects, their fields and the references between them. You can take it by hand with jcmd <pid> GC.heap_dump or automatically on an OOM. Junior 28 What does a thread dump give you, and how do you take one? A thread dump is the state and stack trace of all the threads in the JVM at that moment. When the application freezes, the CPU is at 100% or there is a deadlock, it shows what each thread is doing; you take it with jstack <pid> or jcmd <pid> Thread.print. Junior 29 Which garbage collector is the default in current Java versions? Since Java 9, the default on a server-class machine is G1. If the JVM sees fewer than 2 CPUs or less than 1792 MB of memory, Serial GC is chosen. In Java 8 the default was Parallel GC. Junior 30 List the main garbage collectors in HotSpot and say when you would pick each. Flag / In short / When — Serial: -XX:+UseSerialGC / one thread, all work in the pause / small heap, 1 CPU, CLI utilities; Parallel: -XX:+UseParallelGC / many threads, but in the pause / batch, ETL: overall speed matters, not the pause; G1: -XX:+UseG1GC / regions, a pause goal / most web services; ZGC: -XX:+UseZGC /… Junior 31 How do you turn on the GC log, and what do you read from it first? In Java 9+ with a unified logging flag like -Xlog:gc*:file=gc.log. In the log I first look at the pause duration, how much the heap shrinks after each GC, and whether there is a Full GC. Junior 32 What is the difference between ClassNotFoundException and NoClassDefFoundError? ClassNotFoundException is a checked exception thrown when code tries to load a class dynamically by name (Class.forName) and can't find it. NoClassDefFoundError is an Error thrown when a class that existed at compile time is missing at runtime, or when its initialization failed earlier. Junior 33 What causes the UnsupportedClassVersionError? A class was compiled with a newer Java version, but you are trying to run it on an older JVM. For example, a jar built with Java 21 gives this error on a Java 17 runtime. Junior 34 What is the javap tool for? javap is the JDK's disassembler. It shows the list of methods inside a .class file, the bytecode with -c, and the constant pool and version with -v. It is handy for checking what the compiler actually did. Junior 35 What is HotSpot, and are there other JVM implementations? HotSpot is the main JVM in OpenJDK, and almost all distributions like Oracle JDK, Temurin and Corretto are based on it. There are other JVMs too, such as Eclipse OpenJ9, GraalVM and Azul Prime. Junior 36 List the runtime data areas in the JVM specification. Shared by all threads: the heap and the method area (Metaspace in HotSpot). Per thread: the PC register, the JVM stack and the native method stack. Junior 37 Does the GC close a file or DB connection by itself? No. The GC only returns heap memory; it knows nothing about OS resources (file descriptors, sockets, DB connections). You have to close them yourself with try-with-resources or close(). Junior 38 How do the -D, -X and -XX prefixes in JVM parameters differ from each other? -D sets a system property (-Dspring.profiles.active=prod). -X are non-standard but widespread options (-Xmx, -Xss). -XX are HotSpot's internal settings (-XX:+UseG1GC), and they can change from version to version. Junior 39 Which JDK tools do you know for observing a running Java application? The main ones: jps (list of processes), jcmd (universal diagnostics), jstat (GC statistics), jstack (thread dump), jmap (heap), and graphical tools: JConsole, VisualVM, JDK Mission Control. Junior 40 What is Java Flight Recorder (JFR), and how do you turn it on? JFR is a very low-overhead recorder built into the JVM: it writes events like GC, allocation, locks, I/O and CPU sampling to a .jfr file. You turn it on with the -XX:StartFlightRecording flag, or on a running process with jcmd <pid> JFR.start. Junior 41 Why do these entities cause a StackOverflowError when logged, and how do you fix it? Author.toString() prints the list of books, and each Book.toString() prints the author again: the bidirectional association turns into endless recursion. You have to exclude one side of the association from toString. Strong Junior 42 Does setting a local variable to null after you are done with it help the GC? Usually not. The JIT knows after which point a variable is no longer used and can treat the object as "dead" even before that. Setting null makes sense only for long-lived fields or collection elements. Strong Junior 43 Where is memory leaking in this code? AUDIT is a static list; an entry is added to it on every request but never removed. A static field lives as long as the class does (in practice until the application ends), so the heap slowly fills up. Strong Junior 44 What causes OutOfMemoryError: Metaspace? When the room for class metadata runs out: when the MaxMetaspaceSize limit is reached or the OS doesn't give more memory. Often the cause is classes being generated endlessly or ClassLoaders that were never released. Strong Junior 45 What situation does the "GC overhead limit exceeded" error indicate? The JVM is spending almost all its time (more than 98%) on GC, yet each time it frees less than 2% of the heap. Instead of "freezing and dying slowly", the JVM throws this OOM to stop the program. Strong Junior 46 If "OutOfMemoryError: unable to create native thread" appears, does enlarging the heap help? No, it can even hurt. This error is tied to the OS, not the heap: the stack memory for a new thread, or the number of threads allowed to the process, has run out. The cause is usually threads being created without control. Strong Junior 47 If the container limit is 1 GB, why is setting -Xmx1g a mistake? -Xmx limits only the heap, but beyond the heap the JVM also takes memory for Metaspace, thread stacks, the code cache, GC structures and direct buffers. The total exceeds 1 GB and the Linux OOM killer kills the container with exit 137. Strong Junior 48 How does WeakHashMap work, and why is using it as a cache often a mistake? WeakHashMap holds keys through weak references: if no other strong reference to the key remains, the GC collects it and the entry disappears from the map on its own. But the cleanup depends on whether the key is alive, not the value, so it is not an ordinary cache that "gets cleaned when memory runs low". Strong Junior 49 How much space does an ordinary object take on the heap, and what does it depend on? In 64-bit HotSpot every object has a 12-byte header (with a compressed class pointer), then the fields follow, and the size is padded to a multiple of 8 bytes. That is why new Object() is 16 bytes and an Integer is also 16 bytes, even though an int is only 4 bytes. Strong Junior 50 What does turning on -XX:+HeapDumpOnOutOfMemoryError in a prod service give you, and what should you watch for? The state of the heap at the exact moment of the OOM is written to a file, and then you can see precisely what occupied the memory. What to watch for: disk space for the dump, the file path surviving the container's death, and the sensitive data inside. Strong Junior 51 Why does this code print true the first time and false the second? How does the Integer cache work? Autoboxing goes through Integer.valueOf(), which returns a ready-made cached object for values from -128 to 127. At 127 both variables point to the same object; at 128 two separate objects are created and == compares references. Strong Junior 52 Which objects become eligible for GC after this method finishes? temp and the objects inside list become unreachable as soon as the method returns. The String added to CACHE stays alive through the static field, and the GC will not touch it. Strong Junior 53 How does the JVM behave when stopped with kill -15 versus kill -9, and when do shutdown hooks run? On SIGTERM (kill -15) the JVM shuts down in an orderly way: it runs the registered shutdown hooks and the Spring context is closed. A process cannot catch SIGKILL (kill -9). The kernel kills it immediately and no hook runs. Strong Junior 54 What does this code print? Explain when a class gets initialized. Only main and B run: A.VERSION is a compile-time constant, so A is not initialized at all, while B.count is an ordinary static field and touching it runs B's static block. Strong Junior 55 The code compiled fine, but at runtime it throws NoSuchMethodError. How can that happen? The code was compiled against one version of a library, but at runtime a different version ended up on the classpath, and it lacks that method (or that exact signature). The usual cause is a transitive dependency conflict. Strong Junior 56 A library that worked on Java 8 throws InaccessibleObjectException on Java 17. Why, and what does --add-opens do? Since Java 16-17 the JDK's internal packages are strongly encapsulated: reaching private members through reflection with setAccessible(true) is now forbidden by default. --add-opens opens one specific package of one specific module for reflection. Strong Junior 57 How does "OutOfMemoryError: Requested array size exceeds VM limit" differ from "Java heap space"? This error does not mean the heap is full. It means the requested array length exceeds the maximum the JVM allows (roughly Integer.MAX_VALUE). Making the heap bigger doesn't help, because the array simply can't be that large. Strong Junior 58 What is the difference between strong, soft, weak and phantom references as far as the GC is concerned? When the GC collects it / Where it is used — Strong (Foo f = ...): never, as long as the reference exists / ordinary code; SoftReference: when the heap is tight, before an OOM / memory-sensitive caches; WeakReference: at the next GC, if there is no other strong reference / metadata, listener lists; PhantomReference… Strong Junior 59 What does try/finally look like in bytecode, and why is a return inside finally dangerous? javac copies the finally block onto every exit path (a normal return and an exception) and adds an "any exception" entry to the exception table. If finally contains a return, it silently swallows both the value from the try and any exception that was thrown. Strong Junior 60 What do you gain by setting -Xms and -Xmx to the same value? The heap is allocated at its maximum size from the start, and the JVM doesn't spend time growing or shrinking it while running. On servers this gives steadier latency, but the memory is never returned to the OS. Strong Junior 61 How is unified JVM logging (-Xlog) structured, and what problems besides GC do you use it for? The -Xlog syntax is tags=level:output:decorators:options. Beyond GC, I use it to see where a class was loaded from (class+load), safepoints, container limits (os+container), and JIT and metaspace problems. Middle 62 A Java service is slow for the first requests after startup and gets faster after a few minutes. Why? This is JIT warm-up: at first the bytecode is interpreted, the JVM watches which methods are called often, and then compiles them to native code. On top of that, classes load, caches fill and connection pools fill. Middle 63 How do the C1 and C2 compilers in HotSpot differ, and how does tiered compilation work? C1 compiles fast but optimizes little; C2 is slower but optimizes aggressively based on the profile. Tiered compilation runs a method first through the interpreter, then C1 (collecting a profile), and through C2 if it gets hot enough. Middle 64 How do you read the jstat -gcutil output, and what do you conclude from it? Every N milliseconds jstat prints how full the heap spaces are as a percentage, plus the GC count and time. I look at the trend of the Old (O) column after GCs, whether the FGC count is growing, and how fast the GCT time is growing. Middle 65 How does G1 divide the heap, and what does -XX:MaxGCPauseMillis actually control? G1 splits the heap into equally sized regions (1-32 MB), and each region takes the role of eden, survivor, old or humongous. MaxGCPauseMillis is a target, not a guarantee: G1 chooses how many regions to collect in a single pause to try to fit within it. Middle 66 When do you consider Parallel GC a better choice than G1? For work where pause length doesn't matter but total throughput does: batch jobs, ETL, report generation. Parallel GC spends no CPU on concurrent work and its barriers are lightweight, so it gets more work done in the same time. Middle 67 Does the JVM return free heap memory to the operating system? How does that work in G1 and ZGC? It does, but only in limited cases and never below -Xms. G1 mostly shrinks the heap after a Full GC or Remark, and since JDK 12 it also returns memory through a periodic GC while idle. ZGC uncommits free memory by itself after a certain delay. Middle 68 How do you diagnose a prod server with jcmd? jcmd is a universal tool that attaches to a running JVM. With this one command I get thread dumps, heap dumps, GC statistics, flags, start a JFR recording and get the native memory report. There is no need to restart the application. Middle 69 You opened a heap dump in Eclipse MAT. How do you find out who is holding the memory? First I look at the Leak Suspects report, then the Dominator Tree, which sorts objects by retained size. From the biggest object I use "Path to GC Roots" to find who is holding it. Middle 70 In heap analysis, how does shallow size differ from retained size? Shallow size is the bytes the object itself occupies (header and fields). Retained size is the total memory the GC would free if this object disappeared, that is, all the objects reachable only through it. Middle 71 The service "freezes" from time to time. You take a thread dump. What do you look for in it? I take 3-5 dumps a few seconds apart and compare them: threads stuck in the same stack, threads in the BLOCKED state waiting on one lock, deadlocks the JVM detected, and pool threads that are all busy. Middle 72 How does ThreadLocal used together with a thread pool lead to a memory leak or mixed-up data? Threads in a pool don't die, so a value put into a ThreadLocal lives as long as the thread unless you call remove(). The next request can also see the old value on that same thread. Middle 73 In monitoring, the heap level after each GC keeps rising from day to day. How do you confirm a leak on prod and find its source? First I confirm that the post-GC heap (old gen) graph is a sawtooth, but its lower line keeps climbing. Then I take two class histograms or heap dumps a few hours apart and compare which classes' object counts are growing. Middle 74 Where does the JVM get the memory limit in a container, and what is the benefit of MaxRAMPercentage over -Xmx? Java 10+ (8u191+) reads the container limit from the cgroup files and sizes the heap relative to it. -XX:MaxRAMPercentage=75 adjusts the heap automatically even if the limit changes, while a hard-coded -Xmx has to be corrected by hand every time. Middle 75 -Xmx2g is set, but the process RSS is around 3 GB. Where is the rest of the memory going? The heap is only one part of the JVM's memory. On top of it come metaspace, each thread's stack, the JIT's code cache, the GC's internal structures, direct ByteBuffers and native libraries. Middle 76 Why is leaving remote debugging (JDWP) attached to a prod JVM dangerous, and what do you do instead? Anyone who connects to the JDWP port can execute any code, which is full remote control. A breakpoint also freezes a thread and holds up real requests. On prod I use logs, JFR, thread dumps and, if needed, read-only observation tools. Middle 77 Why is creating an object with new so cheap in Java? What is a TLAB? Each thread gets its own small buffer from eden, a TLAB (Thread-Local Allocation Buffer), and creates objects in it by just bumping a pointer. No lock and no search for free space is needed, so an allocation is a few instructions. Middle 78 When does an object move from the young generation to the old generation? Each minor GC an object survives raises its age by one. When the age reaches the tenuring threshold (up to 15 by default, adjusted dynamically) or the survivor space runs out, the object is moved to the old generation. Middle 79 CPU is 90% busy and the cause is unknown. How do you take a flame graph with async-profiler and how do you read it? I attach async-profiler to the running process, collect CPU samples for 30-60 seconds and get an HTML flame graph. In it, width is the share of CPU time and height is call depth. Wide "plateaus" at the top are the hot spots. Middle 80 What is Epsilon GC, and where might you need a GC that does not reclaim memory at all? Epsilon (JDK 11, JEP 318) allocates memory but never collects it. When the heap runs out, the JVM stops with an OOM. It is useful in performance tests to isolate the effect of GC, to measure allocation, and for very short-lived processes. Middle 81 ZGC can keep pauses under a millisecond no matter how many gigabytes the heap is. How does it pull this off? ZGC does almost all the work (marking, relocating objects and updating references) concurrently with the application. For that it uses colored pointers and a load barrier: if the application touches a relocated object, the barrier fixes the reference on the spot. Strong Middle 82 Shenandoah and ZGC are both low-pause GCs. How do they differ, and when do you choose each? Shenandoah / ZGC — Developed by: Red Hat / Oracle; Concurrent relocation mechanism: forwarding pointer + load-reference barrier / colored pointer + load barrier; Compressed oops: yes / no; Generational mode: experimental in JDK 24, product since JDK 25 / Java 21+, default since 23; Distributions: most OpenJDK builds… Strong Middle 83 What is a humongous object in G1, and what problems do they cause? An object larger than half the region size is humongous. It is placed directly into old, in one or several contiguous regions. If there are many of them, the heap fragments, regions are wasted and unexpected Full GCs appear. Strong Middle 84 "to-space exhausted" or "Evacuation Failure" shows up in the G1 log. What does it mean and what do you do? A young or mixed GC couldn't find a free region to copy the live objects into. G1 leaves the objects in place and the pause gets much longer, and often a Full GC follows. It is a sign that the heap isn't big enough for the live data. Strong Middle 85 When G1 collects only the young generation, how does it find references from old to young? What are the card table and the remembered set? To avoid scanning all of old, G1 uses a write barrier to mark which chunks of memory (cards) had a reference changed. Each region's remembered set stores who points into it from outside, so a young GC looks only at that small set. Strong Middle 86 What is escape analysis, and which optimizations does the JIT do with it? Escape analysis is the JIT working out that an object does not "escape" from the method or the thread. If it doesn't, the JIT doesn't create the object at all but spreads its fields into registers (scalar replacement), and removes unneeded locks. Strong Middle 87 How do inlining and deoptimization work in the JIT, and how can they cause unexpected slowdowns on prod? Inlining means copying the body of the called method into the caller, and it is the foundation of all other optimizations. C2 makes assumptions based on the profile. When an assumption breaks, deoptimization happens: the code goes back to the interpreter and is recompiled. Strong Middle 88 What is a safepoint, and can the application stall for a long time even when the pause in the GC log is short? A safepoint is a state where all Java threads are stopped and the JVM can safely do its work. The pause has two parts: the time it takes to stop the threads (time-to-safepoint) and the work itself. If one thread stops late, all the others wait, and the GC log may show only the second part. Strong Middle 89 A colleague compared two implementations with this code and wrote the result in the PR. Why can't you trust this measurement? There is no warm-up, the JIT may remove the computation entirely because the result isn't used, the first variant is measured in the interpreter and the second after compilation, and GC pauses land by chance. The right way is JMH. Strong Middle 90 What happens when the code cache fills up, and how do you detect it? The JIT can no longer compile new methods: the log says "CodeCache is full. Compiler has been disabled", and new hot code stays in the interpreter. The application doesn't throw an error, but it slowly gets several times slower. Strong Middle 91 Where does "OutOfMemoryError: Direct buffer memory" come from, and how do you investigate it? It is not about the heap. It means the limit for memory allocated off-heap with ByteBuffer.allocateDirect has run out. The usual causes are Netty, NIO channels or gRPC buffers that weren't released, or -XX:MaxDirectMemorySize being too small. Strong Middle 92 How do you analyze growth in the JVM's off-heap memory with Native Memory Tracking (NMT)? I start the JVM with -XX:NativeMemoryTracking=summary, take a jcmd VM.native_memory baseline, and a few hours later compare it with summary.diff. The diff shows exactly which section is growing: Thread, Class, GC, Code, Internal. Strong Middle 93 A pod keeps restarting with "OOMKilled", but there is no Java OutOfMemoryError in the log. How do you analyze this? This is not the JVM but the Linux kernel's OOM killer: the container's total RSS exceeded the cgroup limit and the process was killed with SIGKILL. The heap did not exceed its limit, so the memory is outside the heap: metaspace, threads, direct buffers, malloc. Strong Middle 94 After you redeploy on an application server, why does the old ClassLoader not get collected, and how do you find it in a heap dump? It is enough for one class or object of the old ClassLoader to be held by something, and all the classes it loaded stay in metaspace. The usual culprits: an uncleaned ThreadLocal, a thread that wasn't stopped, a JDBC driver registration, a static cache in a shared loader. Strong Middle 95 When you open a JFR recording in Mission Control, how do you analyze allocation pressure and lock contention? For allocation I group the ObjectAllocationSample events by stack trace to find the places allocating the most bytes. For locks I sort the JavaMonitorEnter and ThreadPark events by monitor class and wait time. Strong Middle 96 What are compressed oops, and why can raising the heap slightly above 32 GB reduce your memory instead of increasing it? On a 64-bit JVM, compressed oops store object references in 32 bits and, thanks to 8-byte alignment, can address a heap of up to 32 GB. When the heap goes beyond ~32 GB, references switch to 64 bits, objects grow and the usable space shrinks. Strong Middle 97 p99 latency has occasional 500 ms spikes. How do you prove whether or not they are caused by GC? I overlay the timestamps of the spikes with the pauses in the GC and safepoint logs. If they match, it's GC. If not, I check in JFR what the threads were waiting on at that moment, and check DB, network and CPU throttling. Strong Middle 98 How does a lambda expression look in bytecode, and what role does invokedynamic play here? The compiler turns the lambda body into a private synthetic method in the class and puts an invokedynamic at the call site. On first execution LambdaMetafactory creates a hidden class at runtime that implements the functional interface, and later calls reuse it. Strong Middle 99 What causes a Full GC in G1, and how do you tell each cause apart in the log? For G1, a Full GC is a sign that the concurrent work didn't keep up. The main causes: no space left after an evacuation failure, no contiguous region found for a humongous object, metaspace filling up, and a System.gc() call. Each is written in the log in parentheses under its own name. Strong Middle 100 What is Application Class Data Sharing (AppCDS), and how does it speed up startup of a Spring Boot service? AppCDS saves the internal representation of loaded and verified classes into an archive file, and on later startups maps them straight into memory. Parsing and verifying classes is skipped, so startup gets 20-40% faster. Strong Middle 101 What is a Java agent, how do premain and agentmain work, and why does Java 21 warn about dynamically loaded agents? An agent is a jar that can change the bytecode of classes, as they load or afterwards, through the Instrumentation API. With -javaagent, premain is called at startup; with attach, agentmain is called in an already running JVM. Since JDK 21, dynamic loading prints a warning because it can compromise the integrity of the JVM. Strong Middle 102 How does a "com.app.User cannot be cast to com.app.User" error come about? In the JVM a class's identity is the pair of its name and the classloader that loaded it. If the same class is loaded by two different loaders, the JVM sees them as two different types and the cast fails. Strong Middle 103 When exactly does a class's static initializer run, and how does the lazy holder idiom rely on that? A static block runs the first time the class is actively used: when an object is created, a static method is called, or a non-constant static field is read. The JVM makes this step thread-safe, and the lazy holder takes advantage of that. Strong Middle 104 The first request gets an ExceptionInInitializerError, and the later ones get NoClassDefFoundError. What does that mean? The class's static initializer threw an exception on the first attempt. The JVM marks the class as being in an error state and, on every later access, throws NoClassDefFoundError without trying again. Strong Middle 105 How do the invokestatic, invokespecial, invokevirtual, invokeinterface and invokedynamic instructions differ? The first four differ in how they pick the method to call: static, exact (private/constructor/super), virtual dispatch and dispatch through an interface. invokedynamic binds the call site at runtime through a bootstrap method. Strong Middle 106 How does calling a method through reflection work, how does it differ from MethodHandle, and what changed in Java 18? Method.invoke checks access and arguments on every call and wraps the arguments in an array. A MethodHandle does the checks once, at creation, and if it sits in a static final field the JIT can inline it like an ordinary call. Since Java 18 (JEP 416), core reflection itself is also built on top of method handles internally. Strong Middle 107 How does the bytecode of these two methods differ, and how is string concatenation compiled after Java 9? In Java 9+, a + b + c turns into a single invokedynamic call (StringConcatFactory). But += inside a loop creates a new String on every iteration, so you still need a StringBuilder there. Strong Middle 108 What are JIT intrinsics, and why do System.arraycopy or the Math methods run faster than similar Java code? An intrinsic is a method the JVM recognizes by name. The JIT doesn't compile its Java body but substitutes hand-written machine code tuned to the processor. SIMD and special CPU instructions (popcnt, crc32, AES) are used this way. Strong Middle 109 How do you read the -XX:+PrintCompilation output, and what can you learn from it? Each line is one compilation event: time, compilation ID, attribute flags (% for OSR, s for synchronized, ! for exception handler, n for native), tier level, method name and bytecode size. "made not entrant" means the code was invalidated. Strong Middle 110 What is auto-vectorization, which loops turn into SIMD instructions, and where does the Vector API fit in? C2 can turn simple array loops (independent operations on elements of the same type) into SIMD instructions, where one instruction processes 4-16 elements at once. It doesn't work on complex loops. For explicit vector code there is the Vector API, but it is still in an incubator module. Strong Middle 111 What are range check elimination and loop unrolling, and how does the JIT speed up array loops? Java must check the index bounds on every array access. C2 analyzes the loop and turns these checks into a single check before the loop (range check elimination), and it spreads the loop body into several copies to reduce the number of jumps (unrolling). Strong Middle 112 What are monomorphic, bimorphic and megamorphic call sites, and how do they affect speed? It depends on how many different classes show up at a call site at runtime: with one, the JIT inlines it directly; with two, it inlines both variants behind an if; with three or more, an ordinary virtual call usually remains and inlining is lost. Strong Middle 113 In the prod log, a NullPointerException shows up as a single line with no stack trace. What is the reason? C2 replaces "internal" exceptions that are thrown often at the same spot (NPE, ArithmeticException, ArrayIndexOutOfBounds, ClassCast) with a preallocated object that has no stack trace. This is the OmitStackTraceInFastThrow optimization, and it is on by default. Strong Middle 114 What is OSR (on-stack replacement), and how does it distort micro-benchmark results? OSR swaps a method stuck inside one long loop for a compiled version in place, without waiting for it to finish. Such code is optimized worse than normally compiled code, so a result measured with a loop inside main doesn't reflect the real situation. Strong Middle 115 What is inside an object header: what do the mark word and the class pointer do? In 64-bit HotSpot the header is an 8-byte mark word and a (compressed) 4-byte class pointer. The mark word holds the identity hash, the GC age and the lock state bits; the class pointer says which class the object belongs to. Arrays have an extra length field. Strong Middle 116 What was biased locking, and why was it disabled in JDK 15 and later removed completely? Biased locking "bound" a lock to the first thread that took it, so reacquiring it didn't even need an atomic CAS. But revocation required a safepoint and complicated the code. Because its benefit shrank in modern applications, it was disabled in JDK 15 (JEP 374), and the code was removed in JDK 18. Strong Middle 117 What does a synchronized block look like in bytecode, and what states does the JVM move a lock through internally? The block turns into monitorenter/monitorexit instructions, and a separate monitorexit is added for the exception path too. Internally the JVM first takes a lightweight lock with a CAS, and if there is contention it "inflates" it into a full monitor and puts the waiting threads to sleep at the OS level. Strong Middle 118 What is premature promotion, and how does it make Old Gen fill up fast? Short-lived objects get moved to Old Gen early, because they don't fit in Survivor or because young GCs happen too often. They die quickly there, but they are cleaned only by the more expensive old/mixed collections. Strong Middle 119 What are the write barrier and the load barrier, which GC uses which, and how does this affect throughput? A barrier is a small piece of code the JIT places around every reference write or read, to tell the GC what the application is doing. Parallel and G1 use a write barrier on reference writes; ZGC relies mainly on a load barrier, and Shenandoah on both. The heavier the barrier, the more work the GC can do concurrently, but the slower the application code gets. Strong Middle 120 What was the CMS collector, why did it have a fragmentation problem, and in which version was it removed? CMS (Concurrent Mark Sweep) marked the old gen concurrently with the application and cleaned the garbage in place, but didn't move objects (no compaction). Over time the old gen would fragment, and if no space could be found for a big object, a long single-threaded Full GC followed. It was deprecated in JDK 9 and removed in JDK 14 (JEP 363). Strong Middle 121 What is G1's cycle: how do young collection, concurrent marking and mixed collection connect with each other? Normally only young GCs run. When Old occupancy exceeds the IHOP threshold, concurrent marking starts and works out which Old regions have the most garbage. The next several mixed GCs clean those Old regions with the most garbage along with the young regions. Strong Middle 122 What does the difference between cgroup v1 and v2 mean for the JVM, and why does an old JDK see the wrong memory limit on new nodes? The JVM reads container limits from cgroup files, and v1 and v2 have different files and structure. Only JDK 15+ and the backported 11.0.16+ and 8u372+ understand cgroup v2. An older JVM can't find the limit on a v2 node and sizes the heap from the memory of the whole node. Strong Middle 123 "Allocation Stall" shows up in the ZGC log. What does it mean and how do you fix it? An application thread asked for space for a new object, but the ZGC concurrent cycle hadn't managed to free any yet, so the thread waited for the GC to finish. It is not a formal pause, but for the user it is the same thing as one. Typical causes: a small heap reserve, a very high allocation rate, or not enough CPU for the GC. Strong Middle 124 What is StackWalker, and how is it better than Thread.getStackTrace() or new Throwable().getStackTrace()? StackWalker (Java 9) gives the stack lazily, as a stream: only the frames you need are read, and a full StackTraceElement[] array isn't created. It is much cheaper when you need the caller class or just a frame or two from the stack. Strong Middle 125 How does building a custom runtime with jlink shrink a container image, and what should you watch out for? jlink builds a runtime from only the JDK modules the application needs: 50-80 MB instead of a 300+ MB JDK. jdeps gives you the list of needed modules, but modules used through reflection and service loading often get missed, and diagnostic tools disappear too. Strong Middle 126 What are these G1 log lines saying, and which one worries you? The young pauses are normal, but to-space exhausted and the Full GC after it mean the live objects the application produces don't fit in the heap. Now you need to check Old occupancy, the allocation rate and humongous allocations. Strong Middle 127 What happens when System.gc() is called in code, and why is blindly turning on -XX:+DisableExplicitGC dangerous? In most GCs, System.gc() triggers a full stop-the-world Full GC. DisableExplicitGC turns it off, but NIO direct buffers try to clean up old buffers through exactly System.gc() when memory runs out. With it turned off, a "Direct buffer memory" OOM can appear. Strong Middle 128 How did the Foreign Function & Memory API (Java 22) change working with off-heap memory compared to ByteBuffer and Unsafe? The FFM API (JEP 454, final in Java 22) manages off-heap memory safely and explicitly through MemorySegment and Arena: there are bounds checks, memory is freed immediately when the arena closes, and there is no 2 GB limit. With ByteBuffer, freeing depended on the GC, and Unsafe gave no protection at all. Strong Middle 129 What secrets does a prod heap dump contain, and what rules do you follow when working with one? A heap dump is a full copy of the process memory: passwords, JWT tokens, API keys, DB connection strings, users' personal data and card numbers can all be in plain text. So I protect it like a copy of the prod database: restricted access, encrypted storage, short retention. Strong Middle 130 What is a hidden class, and what has it changed for classes generated at runtime since Java 15? A hidden class (JEP 371) is created with Lookup.defineHiddenClass. It can't be found by name and other classes can't link to it directly. It can be unloaded on its own, so it is safe and light on metaspace for the classes that lambdas, proxies and frameworks generate. Strong Middle 131 What is nest-based access control (Java 11), and how did it change inner classes' access to private members at the bytecode level? Before Java 11, when an inner class accessed an outer class's private field, javac generated synthetic bridge methods like access$000, because to the JVM they were separate classes. Since Java 11 (JEP 181), classes are declared as a "nest" and the JVM lets the members of one nest access each other's private members directly. Strong Middle 132 How does a switch on a String work in bytecode, and when are tableswitch and lookupswitch chosen? javac turns a String switch into two steps: first a lookupswitch on hashCode(), then an exact check with equals() and a second switch on an internal index. tableswitch is a single jump through an index for dense values, while lookupswitch is a search in a sorted table for sparse values. Strong Middle 133 What are the constant pool and symbolic references in a class file, and when do they turn into real addresses? The constant pool is a table in the class file: string literals, numbers, and class, method and field names. Bytecode calls methods not by address but by a symbolic reference (name + descriptor) in this table. HotSpot resolves them lazily: when an instruction runs for the first time it is bound to the real class/method and the result is cached. Strong Middle 134 What is JMX, and what do you configure to monitor a prod JVM through JMX safely? JMX is a standard that exposes the internal state of the JVM and the application through MBeans: heap, GC, threads, connection pools. Remote connections are closed by default; if you open them and leave out authentication and TLS, you open the way to remote code execution. On prod I usually keep JMX local and export metrics through Micrometer/Prometheus. Strong Middle 135 A Java service is pinning one core at 100%. How do you find which thread and which code is to blame? At the OS level you find the native thread ID using the most CPU, convert it to hex, match it with the nid in the thread dump and look at the stack. Taking several dumps and comparing them, or async-profiler, makes this more reliable. Strong Middle 136 What is safepoint bias, and why do some profilers send you to the wrong method? Some profilers take a stack sample only when the thread has stopped at a safepoint. So they point at places that have a safepoint check (the end of a loop, a method return), and the real hot code stays invisible. async-profiler and JFR are mostly free of this problem. Strong Middle 137 How do sampling and instrumenting profilers differ, and when do you use each? A sampling profiler takes snapshots of thread stacks every N milliseconds: low overhead, usable on prod, but the result is statistical. An instrumenting profiler adds code at every method entry and exit: call counts are exact, but the overhead is large and it makes small methods behave differently from how the JIT would run them. I look for CPU problems with sampling, and for exact call counts with instrumentation. Strong Middle 138 How do you find out the actual values of JVM flags, and what does the "ergonomic" mark in the PrintFlagsFinal output mean? java -XX:+PrintFlagsFinal -version, or jcmd <pid> VM.flags -all on a running process, shows the final value of every flag. Next to each value is its source: default, command line or ergonomic; the last means the JVM chose the value itself based on the machine's resources. Strong Middle 139 With a CPU limit of 2 in a container, how many cores does the JVM see, and how does that affect the GC and thread pools? Java 10+ (8u191+) reads the cgroup limits and returns availableProcessors() based on the CPU quota. That number sets the size of the GC threads, the JIT compiler threads, ForkJoinPool.commonPool and many framework pools, so if the limit is wrong, everything is sized wrong. Strong Middle 140 What does bytecode verification check, and why was turning it off with -Xverify:none deprecated? When a class loads, the verifier checks that its bytecode follows the JVM rules: the stack doesn't overflow, types match, jumps stay inside the method, private members aren't accessed without permission. Turning it off speeds up startup a little, but broken or malicious bytecode could crash the JVM, so -Xverify:none was deprecated in JDK 13. Strong Middle 141 For a service with a 24 GB heap and a p99 latency that must not exceed 50 ms, how do you choose between G1 and generational ZGC? First I measure G1's actual pause distribution today and what share of the latency budget the pauses take. If G1's pauses fit the budget, I keep it and tune it; if they don't, I try ZGC as a canary on real traffic and compare p99, CPU and memory use. Senior 142 A batch job processing a million rows with Hibernate fills the heap and crashes with an OOM. How do you analyze and fix it, from the JVM side and the code side? The usual cause is the persistence context: every loaded entity and its snapshot stay in memory until the session closes. In a heap dump or histogram you see EntityEntry and the entity classes. The fix is working in chunks with flush()/clear(), StatelessSession, reading with scroll/stream, or a DTO projection. Senior 143 How do you determine the heap size for a new service? What is wrong with the "let's set 8 GB, it'll be enough" approach? I derive the heap from the live set: I measure the live data left after a Full GC or old collection under load, and add 2-4 times that as headroom, depending on the GC type. A guessed big heap hides problems, wastes money on memory and breaks the container budget. Senior 144 How does ThreadPoolExecutor's unbounded queue lead to a slow OOM, and how do you design the pool? Inside Executors.newFixedThreadPool there is an unbounded LinkedBlockingQueue. If tasks arrive faster than they are processed, the queue grows without limit, and each task holds its request data. The heap fills slowly, and latency goes up first. You need to bound the queue and have an explicit policy for when it is full (reject, backpressure). Senior 145 Your Java service takes 40 seconds to start, which is too slow for autoscaling. How do you choose among CDS, AOT cache, CRaC and GraalVM native image? First I measure where the time goes: class loading, the Spring context, DB connections or JIT warm-up. I start with the cheap options (AppCDS/AOT cache, lazy init, turning off needless auto-configuration); I take CRaC and native image only if their operational complexity pays off. Senior 146 When is it worth reducing a high allocation rate, and how do you do it without hurting code quality? It is worth it when the profile shows the GC taking a noticeable share of the CPU or latency budget. I find the 3-5 biggest allocation sources with JFR or async-profiler and fix only those; I don't introduce a "don't create objects" rule across the whole codebase. Senior 147 A service holds a Map<Long, Long> with several million entries keyed by ID, and half the heap is wrapper objects. How do you reduce the memory? Each Long key and value is a separate 24-byte object, on top of a 32-byte HashMap.Node and the table reference. So one 16-byte pair becomes about 85 bytes. Primitive collections (fastutil, Eclipse Collections, HPPC) or sorted long[] arrays take several times less space and put almost no load on the GC. Senior 148 A service holds a 10 GB on-heap cache and GC pauses have become a problem. How do you decide between moving to an off-heap cache, shrinking the cache, or moving it to an external cache? First I measure the cache's real hit rate and the size it actually needs; often shrinking it is enough. If necessary I try switching the GC (for example to ZGC). I take an off-heap cache if the serialization cost and complexity are worth it; if the cache has to be shared across replicas, I choose an external cache like Redis. Senior 149 When you move a service to virtual threads, what do you check at the JVM level: pinning, memory and ThreadLocal? Virtual threads help in code with a lot of blocking I/O, but pinning can tie up carrier threads, heavy objects in a ThreadLocal can get copied a million times, and the resources underneath (the DB pool) may not survive unbounded parallelism. I check these with JFR and a load test. Senior 150 How do you make a move from Java 17 to 21, or to a new GC flag, safe on prod? I treat a JVM change like a code release: I deploy it separately, with no other changes, collect the same metrics (p99, CPU, RSS, GC time) before and after, roll out gradually through a canary, and keep a quick way back ready. Senior 151 The Kubernetes liveness probe is killing Java pods during long GC pauses or warm-up. How do you configure the probes? Liveness should answer only "is the process in an unrecoverable state", not "is it slow". I point it at a lightweight endpoint with no external dependencies, set the timeout and failureThreshold well above the worst pause in the GC log, and use a startupProbe for warm-up. Senior 152 After moving to a new JDK patch or feature release, the service's throughput dropped 15%. How do you hunt for the regression at the JVM level? First I prove that the regression comes from the JDK: the same artifact, the same load, only the JDK differs. Then I compare the two versions' flag defaults, GC numbers, JIT compilation and CPU profile side by side. The cause often turns out to be a changed default or a JIT difference in one hot method. Senior 153 How do you catch performance regressions in CI before they reach prod: JMH, allocation and GC metrics? Three layers: JMH benchmarks with -prof gc for critical code (time and allocation per operation), allocation budgets in tests, and a nightly load test with GC and latency numbers. Allocation numbers are much more stable than time, so I often put the gate on those. Senior 154 How does generational ZGC in Java 21 differ from plain ZGC, and when does it make sense to move to it? Generational ZGC splits the heap into young and old and collects young objects often and cheaply. As a result, on the same heap, CPU use and allocation stalls go down; starting with JDK 23 it is the default ZGC mode. Senior 155 While this method runs, other threads and the GC wait for a long time. What is the cause? A loop with an int counter becomes a "counted loop" in the JIT and its safepoint poll may be removed. Then, when the GC wants to stop all threads, this thread doesn't reach a safepoint until the loop finishes, and the whole JVM waits. Senior 156 In a service that uses exceptions heavily for validation and control flow, CPU and allocation shot up under load. What do exceptions cost in the JVM, and how do you change the design? The main cost of an exception is fillInStackTrace: the JVM walks the whole stack and records the frames, and then writing to the log turns the stack trace into a string. On a deep Spring stack that is microseconds and kilobytes. For expected cases (validation, "not found") you use result types, and exceptions are left for truly exceptional situations. Senior 157 What load does logging on a hot path (string concatenation, MDC, a synchronous appender) put on the JVM, and how do you reduce it? Even with the log level off, the arguments may still be computed, MDC and formatting create objects on every request, and a synchronous appender ties the thread to disk or network I/O. Parameterized logs, an asynchronous appender for delivery, sensible levels and measurement cut the load noticeably. Senior 158 An in-process cache has to be bounded in bytes, not in number of elements. How do you estimate the real size of an object graph, and how do you configure the cache? I measure object sizes on samples with JOL, work out the retained size, and look at the average and the heavy-tailed distribution. Then in Caffeine I set an approximate budget with maximumWeight and a cheap weigher, and check the result against the real size in the heap. Senior 159 You need to look at the machine code the JIT generated. How do you work with hsdis, PrintAssembly and JITWatch, and when is it worth it? -XX:+PrintAssembly with the hsdis disassembler library prints the JIT code as assembly, and JITWatch reads the LogCompilation XML and shows the inlining and escape analysis decisions next to the source code. This is the last step, worth it only when a profile and JMH have led you to exactly one hot method. Senior 160 The sun.misc.Unsafe memory methods were deprecated (JEP 471). What does that mean for your libraries and services? In JDK 23, Unsafe's memory-access methods were deprecated for removal. From JDK 24 a warning appears on the first call, and in later versions they will throw errors and then be removed. The replacements are VarHandle (heap) and the FFM API (off-heap). For services, the main work is finding which dependencies use Unsafe and updating them. Senior 161 Your company has 60 Java services and every team sets JVM flags its own way. How do you standardize this? I provide a common base image with good defaults (a container-friendly heap percentage, GC log, a dump on OOM, JFR). Teams change only what is allowed and documented, and changes come with evidence. Staff 162 You are planning to move the fleet from Java 21 to Java 25 LTS. Which JVM-level changes do you expect to benefit from, and what carries risk? Benefits: virtual threads no longer pin on synchronized, the AOT cache speeds up startup, compact object headers shrink the heap, and generational Shenandoah became a product feature. Risks: non-generational ZGC and the Security Manager were removed, there are warnings for Unsafe and JNI, and agents and bytecode libraries must support the new class file version. Staff 163 How do you match requests/limits and JVM settings for a Java service in Kubernetes? I set the memory limit based on the JVM's whole footprint: the heap is 60-75% of the limit through MaxRAMPercentage, and the rest goes to native memory. I set the CPU limit carefully, because throttling slows down the GC and JIT threads too. Staff 164 How do you choose a JDK distribution (Temurin, Corretto, Zulu, Oracle JDK, GraalVM) for a company? They all come from the same OpenJDK code, so the technical difference is small. The decision comes down to the license, how fast and for how many years security patches are released, the support contract, the extra features needed (CRaC, Shenandoah, native image) and the quality of the container images. Staff 165 The company's shared library has to work on Java 17, 21 and 25 services at the same time. How do you use --release, multi-release JARs and toolchains? I compile the library with --release 17 for the lowest supported version, put the places that need a new API into the META-INF/versions/21 part of a multi-release JAR, and test on all target JDKs in CI. Toolchains make the build independent of the local JDK. Staff 166 Someone proposed moving a long-running, high-load API service to GraalVM native image. How do you evaluate it? In a long-running service, native image's main benefit, fast startup, hardly matters, while peak throughput and diagnostic capabilities may be lost. I measure memory savings and operational cost, and then decide. Staff 167 You want to keep JFR on permanently in prod and build continuous profiling for the whole fleet. How do you design it? On every JVM a low-overhead JFR recording runs in circular mode, and an agent takes it periodically or on an event and sends it to central storage. The main questions are overhead, storage size, personal data and how easy it is to search. Staff 168 A service with a 64 GB heap has a slow leak, but taking a heap dump causes a 40-second pause. How do you investigate? Before a dump, I work with cheap signals: class histograms, JFR's OldObjectSample event and an allocation profile. If I need a dump, I take the instance out of traffic first, or reproduce the same leak on staging with a small heap. Staff 169 One JVM with a 128 GB heap or eight JVMs with 16 GB each: which is better, and what do you base the decision on? The answer depends on the nature of the data: a big shared in-memory state (a cache, an index) may call for one big JVM, while for stateless services many smaller instances are more stable and easier to manage. Staff 170 When running a JVM with a big heap on a multi-socket (NUMA) server, what do you pay attention to, and what does -XX:+UseNUMA give you? In NUMA each processor socket has its own memory, and accessing another socket's memory is slower. With -XX:+UseNUMA the JVM allocates objects close to the socket of the thread that created them. Parallel, G1 (JDK 14+) and ZGC support it. Often a simpler solution is a separate, smaller JVM per socket. Staff 171 In a Netty-based service the heap is normal, but pods get OOMKilled. How do you find a direct memory leak, and how do you prevent it? First I confirm with NMT and BufferPool metrics that direct memory is growing, then I turn on Netty's ResourceLeakDetector to find ByteBufs that weren't release()d. In the long run you need limits and code rules. Staff 172 Your services call native libraries through JNI or FFM, and every now and then the whole JVM crashes. What architectural decisions do you make for stability? Native code is outside the JVM's protection: an error in it isn't an exception, it is the death of the whole process. I put the native part behind a minimal, verifiable boundary, move it to a separate process if possible, grant permission explicitly with --enable-native-access, and prepare diagnostics and automatic recovery for crashes. Staff 173 A Java process's RSS grows over time, while NMT shows stable memory. What role do glibc malloc arenas play here? glibc creates a separate malloc arena for each group of threads and doesn't always return freed memory to the OS. In a Java process with many threads, this fragmentation pushes RSS well above what NMT shows. Staff 174 You are designing a system that loads and updates plugins at runtime. How do you prevent classloader leaks? Each plugin is loaded in its own classloader, and when it is removed no strong reference to it may remain. The main enemies are static registries, ThreadLocals, threads, JDBC drivers and cached reflection objects. Staff 175 Two pods started from the same image behave differently under the same load: one is always slower. What differences do you look for on the JVM and infrastructure side? First I check that they really are "the same": node type, CPU model, cgroup limits, the ergonomic values the JVM chose. Then random differences inside the JVM (JIT decisions, heap state) and neighboring workloads: CPU steal, throttling, a noisy neighbor. The cause often turns out to be the node or the ergonomics. Staff 176 Splitting a monolith into 15 microservices is being proposed. How do the JVM footprint and infrastructure cost change, and how do you calculate it? Every JVM has an "idle" cost: metaspace, code cache, JIT and GC threads, the framework context, a minimal heap. For a Spring Boot service that is typically 200-400 MB of RSS plus the startup time. 15 services × replicas multiplies this base cost. I measure that cost and compare it with the business benefit; if needed I also add shrinking the footprint to the plan. Staff 177 Which metrics do you collect for JVMs at the platform level, and which do you alert on? I alert on symptoms: GC pauses breaking the SLO, steady growth of heap after GC, the share of time going to GC, and OOMs/restarts. The other metrics sit on the dashboard for investigation. Staff 178 In the company there is a proposal: "Java eats a lot of memory, so we'll write new services in Go". How do you evaluate this from the JVM's point of view? First I measure what "eats a lot" is based on. Often the cause is a badly configured heap, extra frameworks and the container budget, not the language itself. Then I compare the real difference (RSS, CPU, startup, throughput) on the same task, and decide together with the team's skills, the ecosystem and the operational cost. Staff 179 How do you draw up a plan to move 30 services from Java 11 to Java 21, and what risks do you expect from the JVM side? First I find all the problems on one pilot service, and then I migrate in waves with a common base image and a checklist. The main risks are removed flags, strong encapsulation, old libraries and changes in GC behavior. Staff 180 The Security Manager was removed completely in JDK 24. Your platform runs users' plugins or scripts. How do you do isolation now? The Security Manager was never a reliable sandbox, and now it is gone entirely (deprecated in JEP 411, removed in JEP 486). Untrusted code can't be protected within one JVM, so I move isolation to the process or container level, and inside the JVM I give only a restricted API (a DSL, WASM, a GraalVM polyglot sandbox). Staff 181 You want to use the Vertical Pod Autoscaler or in-place resize for Java pods in Kubernetes. How does the JVM adapt to memory and CPU changes? The JVM fixes the maximum heap at startup and doesn't grow it while running. If the memory limit is raised, the heap doesn't change, and if it is lowered there is a risk of OOMKilled. Newer JDKs re-read the CPU count periodically, but pool sizes are often fixed at startup. So in practice VPA for memory works through a restart. Staff 182 The JVM crashed and left an hs_err_pid file. How do you read it, and what are your next steps? First I look at the crash cause (SIGSEGV, SIGBUS, native OOM) and the frame and thread that crashed. Depending on whether the frame is in the JVM itself, in JIT code or in a native library, I pick the path: updating the JDK, excluding the method from compilation, or replacing the library. Staff 183 finalize() was deprecated. When designing a library that holds native resources, how do you organize cleanup? The main mechanism is AutoCloseable and try-with-resources: the resource is closed at a known time. Cleaner is added only as a safety net, for cases where the user forgot close(). Staff 184 A team wants to write a "self-cleaning" cache based on SoftReference. How do you evaluate that idea, and what do you suggest instead? SoftReferences hand the cache policy to the GC: they are cleared only under heap pressure and in an unpredictable way. As a result the heap stays full all the time and the GC gets heavier. A size-bounded cache (Caffeine) or an external cache is better. Staff 185 This JMH benchmark shows the new parser is 50 times faster. Do you trust the result? No. Because the result isn't used, the JIT may remove the computation as dead code, and because the input is a constant, constant folding applies too. You need to return the result or pass it to a Blackhole, and read the input from a @State. Staff 186 The load test team reported "the service handles 5000 RPS". What questions do you ask from the JVM's point of view? I ask how long the test ran, whether warm-up was excluded from the numbers, whether a steady state was reached, and how the GC behaved. A 10-minute test doesn't show old gen filling up, Full GCs or slow leaks. Staff 187 In a service that serves many tenants in one JVM, one tenant with heavy requests fills the whole heap and harms the others. How do you protect against this? There is no memory isolation between tenants inside a JVM, so protection is built at the application level: limits on request size and result size, per-tenant concurrency quotas, streaming, and, if needed, moving heavy tenants to a separate pool or deployment. Staff 188 After an OutOfMemoryError, should you leave the JVM running or kill it right away? What policy do you choose for the platform? I usually choose to kill it right away: -XX:+ExitOnOutOfMemoryError and a heap dump before it. After an OOM the application's state is uncertain, and the orchestrator brings up a clean instance in a few seconds. Staff 189 In a service like trading or an ad auction, p99.9 latency must not exceed 5 ms. How do you prepare the JVM for this? I remove the sources of pauses one by one: minimal allocation, a concurrent GC (generational ZGC) or an almost GC-free mode, warm-up before startup, watching safepoints and JIT deoptimization, and at the OS level CPU isolation, huge pages and an environment without swap. I measure every step by p99.9, not by the average. Staff 190 In Kubernetes, heap dumps, JFR recordings and GC logs filled the node's disk and caused other pods to be evicted. How do you build a diagnostic files policy at the platform level? A separate, size-limited place for diagnostic files (an ephemeral storage limit or a separate volume), rotating logs and JFR size limits, and moving a heap dump to object storage right away and deleting it locally. I set a maximum size and a retention period for each file type. Staff 191 How do Transparent Huge Pages on Linux relate to the JVM's large pages setting, and why does THP sometimes worsen latency? Large pages reduce TLB misses and speed up an application with a big heap. But in always mode THP makes the kernel merge and defragment pages in the background, which causes unexpected stalls. For the JVM, the madvise mode with -XX:+UseTransparentHugePages is safer. Staff 192 If most of the heap is Strings, how can you save memory at the JVM level, and what do you change in the application? Since Java 9, compact strings store Latin-1 text with 1 byte per character. G1 and some other collectors merge identical internal arrays with String deduplication. But the biggest win is usually at the application level: replacing repeated values with an enum, a dictionary or a canonical copy. Staff 193 After adding multi-threaded counters, throughput dropped unexpectedly. If you suspect false sharing, how do you check and fix it? If fields written by different threads sit in the same 64-byte cache line, the cores keep pulling that line away from each other. I look at the object layout with JOL and at cache misses with perf, and then separate the fields with @Contended, padding, or striping as in LongAdder. Staff 194 What risks do you assess before adding an APM or OpenTelemetry Java agent to the whole fleet? The agent changes the bytecode of every loaded class: this raises startup time, metaspace and code cache, CPU and allocation, and sometimes breaks JIT optimizations. I measure the overhead, limit the scope of instrumentation and turn it on step by step. Staff 195 How do ScopedValue and structured concurrency change context passing built on ThreadLocal? How do you plan the migration in a big codebase? ScopedValue (final in JDK 25, JEP 506) binds a value immutably, only for the duration of an explicit block: cleanup can't be forgotten, it is cheap with virtual threads, and it is inherited safely by child tasks. Structured concurrency (still a preview in JDK 25) provides this inheritance. I start the migration by listing all the ThreadLocals and the framework boundaries. Staff 196 What problems are there in the JVM settings of this Dockerfile? The heap equals the container limit, so there is no room for native memory and the pod gets OOMKilled. Because exec is missing, the JVM isn't PID 1 and doesn't receive SIGTERM, and the GC log and dumps are lost together with the container. Staff 197 Can a long GC pause in one service turn into an incident across the whole distributed system? Through what mechanisms, and how do you protect against it? Yes. During the pause the instance sends no heartbeat, requests time out and clients retry; as a result leader election, a Kafka rebalance and a retry storm begin. The protection is making timeouts and retries resilient to pauses, and shortening the pauses themselves. Staff 198 Memory leaks keep repeating across several teams. What patterns do you identify, and what team rules and guardrails do you set up to prevent them? Most leaks come from a few patterns: unbounded caches and collections, listeners that were never unregistered, ThreadLocal, metrics with unbounded cardinality, unbounded queues and unclosed resources. I collect them from postmortems and close them with static analysis rules, shared library primitives, and automatic signals in tests and prod. Staff 199 You are writing a runbook for the on-call team for JVM-related incidents. What do you put in it? Short steps ordered by symptom: first collect evidence (thread dump, GC log, JFR, NMT), then restore service (take the pod out of traffic, restart), then deep analysis. The commands must be ready to copy. Staff 200 A service generates many Groovy scripts, dynamic proxies and lambdas at runtime, and metaspace grows by the hour. How do you analyze it and how do you change the design? First I find which classloaders and which classes are multiplying with VM.classloader_stats and VM.metaspace. The cause is usually a new class being generated on every request; the fix is caching the compilation result and limiting the number of classloaders. Staff