Prev Next

Java / Java Performance Tuning: From Profiling to Optimization Interview questions

Last updated

1. What is Java performance tuning? 2. What are the key metrics used to measure Java application performance? 3. What is profiling in Java? 4. List the common tools used to profile Java applications? 5. What is Java Flight Recorder? 6. What is a performance baseline? 7. What are the generations of the Java heap? 8. What is garbage collection in Java? 9. What are the types of garbage collectors in the HotSpot JVM? 10. What is the JIT compiler in the JVM? 11. What is the purpose of the -Xms and -Xmx flags? 12. What is a stop-the-world pause? 13. What is a memory leak in Java? 14. What is a heap dump? 15. What is a thread dump? 16. What is JMH? 17. Define Amdahl's Law in the context of performance tuning? 18. What is Metaspace? 19. What is the difference between sampling and instrumentation profiling? 20. Why is safepoint bias a problem for some Java profilers? 21. How do you read a flame graph? 22. How does tiered compilation work in HotSpot? 23. How does the G1 garbage collector work? 24. When would you choose ZGC over G1? 25. What is the difference between Parallel GC and G1 GC? 26. How do you enable and read GC logs? 27. Why does a high allocation rate hurt Java performance? 28. How does escape analysis reduce object allocation? 29. Why is autoboxing a performance concern in Java? 30. Why should you set the initial capacity of a HashMap or ArrayList? 31. How do you size a thread pool? 32. What is lock contention and how do you detect it? 33. How do virtual threads change performance tuning for blocking workloads? 34. Why is a parallel stream not always faster? 35. How does connection pooling improve database performance? 36. What is the N+1 query problem and how do you fix it? 37. How do you troubleshoot high CPU usage in a Java process? 38. How do you troubleshoot an OutOfMemoryError? 39. How do you find a memory leak using a heap dump? 40. Why do hand-written microbenchmarks give misleading results? 41. Explain the lifecycle of an object in a generational garbage collector? 42. Explain the internal working of TLAB allocation? 43. What is false sharing and how do you avoid it? 44. How can you reduce GC pause times in G1? 45. What happens when the JIT compiler deoptimizes code? 46. How do you tune the JVM for containers like Docker and Kubernetes? 47. How can you optimize JVM startup time? 48. Explain the internal working of card tables and remembered sets? 49. How do you troubleshoot native memory growth in a JVM? 50. Explain a systematic workflow for Java performance tuning, from profiling to optimization?

1. What is Java performance tuning?

Java performance tuning is the process of measuring an application, finding what limits its speed or resource usage, and changing code, configuration, or JVM settings until it meets a defined target such as latency, throughput, or memory footprint.

It is a loop, not a one-time task: measure, find the bottleneck, change one thing, measure again. Tuning without measurement is guesswork, and guesses tend to speed up code that was never the problem.

Work usually happens at four layers:

  • Application code - algorithms, data structures, object allocation
  • Libraries and I/O - database access, serialization, remote calls
  • JVM - heap size, garbage collector, JIT behavior
  • OS and container - CPU and memory limits, file descriptors

Start with the biggest bottleneck at the highest layer. A better query or algorithm almost always beats any JVM flag.

Take quiz
What should happen before you change any code or JVM flag when tuning?
Measure current behavior and identify the real bottleneck
Switch to the newest garbage collector
Increase the heap to the maximum available memory
Rewrite the loop that looks the slowest
Which layer usually gives the biggest gain on a slow Java service?
The thread stack size
Application logic and data access, such as a better algorithm or query
The number of GC worker threads
Individual JIT compiler flags

2. What are the key metrics used to measure Java application performance?

The key metrics are latency, throughput, resource utilization, memory footprint, and startup or warm-up time, along with GC numbers such as pause time and the share of time spent in GC.

Metric What it tells you Typical measure
Latency How long one request takes p50 / p95 / p99 response time
Throughput Work completed per unit of time Requests or transactions per second
CPU utilization How busy the cores are % CPU, run queue length
Memory footprint Heap plus native memory in use RSS, heap used after GC
GC behavior Cost of memory management Pause time, % time in GC
Startup / warm-up Time until the app reaches full speed Seconds to ready, time to steady state

Prefer percentiles over averages for latency. An average of 50 ms can hide a p99 of two seconds, and that is what your slowest users feel.

Latency and throughput can pull in opposite directions, so decide which one your service is judged on before tuning.

Take quiz
Why are p95 and p99 latencies preferred over the average?
Percentiles always equal the average anyway
Averages cannot be calculated for HTTP requests
Averages hide slow outliers that real users still experience
Percentiles are cheaper for the JVM to compute
Which metric measures the amount of work completed per unit of time?
Latency
Warm-up time
Memory footprint
Throughput

3. What is profiling in Java?

Profiling means measuring a running Java program to see where it spends CPU time, allocates memory, waits on locks, or blocks on I/O. The result is a ranked list of hot spots, so you optimize what actually matters instead of what looks slow.

Common kinds of profiling:

  • CPU profiling - which methods burn the most CPU cycles
  • Allocation profiling - which code paths create the most objects and bytes
  • Lock profiling - where threads wait to enter synchronized blocks or locks
  • Wall-clock profiling - where time goes, including sleeping and waiting on I/O

Profile under realistic load and realistic data. A profile taken on a laptop with ten database rows mostly points at the wrong problem. Also remember that every profiler adds some overhead, which is why low-overhead sampling is the usual starting point.

Take quiz
Which kind of profiling shows time spent waiting on I/O as well as running?
CPU profiling
Heap-dump analysis
Allocation profiling
Wall-clock profiling
Why should profiling use realistic load and data?
Profilers refuse to run on small inputs
Hot spots shift with data volume and concurrency
The JIT compiler is switched off for small data
Realistic data removes the need for GC logs

4. List the common tools used to profile Java applications?

Most teams combine a sampling profiler, the JDK's built-in tools, and a heap analyzer:

  • Java Flight Recorder (JFR) + JDK Mission Control - built into the JDK, low overhead, suitable for production
  • async-profiler - sampling profiler for CPU, allocation, and locks, with flame graph output
  • VisualVM - free GUI for sampling, thread views, and heap dumps
  • JProfiler and YourKit - commercial profilers with detailed memory and database views
  • IntelliJ IDEA Profiler - runs async-profiler and JFR from inside the IDE
  • jcmd, jstack, jmap, jstat - JDK command-line tools for thread dumps, heap dumps, and GC statistics
  • Eclipse MAT - heap dump analysis and leak detection
  • JMH - not a profiler, but the standard tool for microbenchmarks

For a first look at a production problem, JFR or async-profiler plus a few thread dumps answers most questions without attaching anything heavy.

Take quiz
Which tool is used to analyze heap dumps and find leak suspects?
jps
JMH
Eclipse MAT
jstat
Which built-in JDK feature is designed for low-overhead recording in production?
jarsigner
javap
jlink
Java Flight Recorder

5. What is Java Flight Recorder?

Java Flight Recorder (JFR) is a built-in, event-based recording framework inside the JVM. It captures diagnostic and profiling data with very low overhead, typically around 1% with the default settings. It has been open source since JDK 11 and was also backported to OpenJDK 8u262.

It records events such as GC phases, object allocation, lock waits, thread parking, file and socket I/O, exceptions, and periodic stack samples. You can start it at launch or on a running JVM:

java -XX:StartFlightRecording=duration=60s,filename=app.jfr -jar app.jar

jcmd <pid> JFR.start name=r1 duration=60s filename=app.jfr
jcmd <pid> JFR.dump name=r1 filename=now.jfr

Open the .jfr file in JDK Mission Control, or inspect it from the terminal with jfr summary and jfr print.

Because the overhead is small, you can leave a continuous recording on (for example with maxage=1h) and dump it after an incident, much like an aircraft's flight recorder.

Take quiz
Which command starts a recording on an already running JVM?
jcmd <pid> JFR.start
jstack <pid> --record
jmap -jfr <pid>
jstat -jfr <pid>
Why is JFR considered suitable for production use?
It pauses all application threads while recording
Its overhead is low, typically around 1% with default settings
It only works in test environments
It requires bytecode instrumentation of your source

6. What is a performance baseline?

A performance baseline is a recorded set of measurements for the application under a known load, configuration, and environment, taken before you change anything. Every later change is judged against it.

A useful baseline records:

  • Workload - request mix, concurrency, data size
  • Environment - hardware, JVM version and flags, container limits
  • Results - latency percentiles, throughput, CPU, heap after GC, GC pause statistics

Run it several times to see the natural run-to-run noise. If two runs of the same build differ by 8%, a "5% improvement" proves nothing. Keeping baselines in CI also lets you catch regressions the day they are introduced.

Take quiz
Why should a baseline test be repeated several times?
Because the JVM ignores the first measurement
To grow the heap gradually
To measure run-to-run variance so small gains are not mistaken for improvements
To warm up the disk cache of the build server only
Which item belongs in a baseline record?
The names of the engineers who ran the test
Only the line count of the source code
Only the average CPU on a developer laptop
JVM version, flags, workload, and measured latency percentiles

7. What are the generations of the Java heap?

The heap is split into a young generation and an old (tenured) generation. The split exists because of the weak generational hypothesis: most objects die young, so collecting a small young area often is cheaper than scanning everything.

Region Holds Collected by
Eden Newly allocated objects Minor (young) GC
Survivor S0 / S1 Objects that survived at least one minor GC Minor GC, copied between the two spaces
Old generation Long-lived objects Major, mixed, or full GC

With Parallel GC the defaults are -XX:NewRatio=2 (old is twice the young size) and -XX:SurvivorRatio=8 (eden is eight times one survivor space). Metaspace is not part of the heap. G1 is still logically generational but uses regions, and ZGC became generational in JDK 21.

Take quiz
Where are newly allocated objects normally placed?
Eden
The old generation
Metaspace
Survivor space S1
What does the weak generational hypothesis state?
Large objects die before small ones
Most objects die young
All objects live about the same time
Old objects die first

8. What is garbage collection in Java?

Garbage collection (GC) is the JVM's automatic memory reclamation. It finds objects that are no longer reachable from any GC root and frees their memory, so you never call free() yourself.

GC roots include local variables on thread stacks, static fields, and JNI references. Anything reachable from a root stays alive; everything else is garbage. Depending on the collector, live objects are then copied, or the dead space is swept and compacted.

GC has a cost: it uses CPU and may pause application threads. It also does not prevent leaks. An object that is still referenced, say from a static map, will never be collected even if your code never uses it again.

Take quiz
When is an object eligible for garbage collection?
After System.gc() has been called once
When it is larger than the survivor space
When it is no longer reachable from any GC root
When its method finishes, even if a static field still references it
Which of these is a GC root?
A method that was never called
An unreferenced object in Eden
A string that was never printed
A local variable on a live thread's stack

9. What are the types of garbage collectors in the HotSpot JVM?

HotSpot ships several collectors, each tuned for a different goal. You pick one with a JVM flag.

Collector Flag Best suited for
Serial -XX:+UseSerialGC Small heaps, single-CPU or tiny containers
Parallel -XX:+UseParallelGC Batch jobs where throughput matters most
G1 -XX:+UseG1GC General-purpose services; balances pauses and throughput
ZGC -XX:+UseZGC Very low pauses and large heaps
Shenandoah -XX:+UseShenandoahGC Low pauses; not included in every vendor build
Epsilon -XX:+UseEpsilonGC No-op collector for tests and benchmarks

G1 has been the default on typical server machines since JDK 9. CMS was removed in JDK 14.

Take quiz
Which collector has been the HotSpot default on typical server machines since JDK 9?
G1
Serial
Epsilon
ZGC
In which JDK version was the CMS collector removed?
JDK 8
JDK 14
JDK 21
JDK 11

10. What is the JIT compiler in the JVM?

The JIT (just-in-time) compiler turns frequently executed bytecode into native machine code while the program runs. The JVM starts by interpreting bytecode, counts how often methods are called and loops repeat, and compiles the hot ones.

HotSpot has two compilers:

  • C1 - compiles quickly with light optimization
  • C2 - compiles slowly but applies aggressive, profile-guided optimization such as inlining, loop unrolling, and escape analysis

The practical effect is warm-up. A freshly started service is slower until its hot paths are compiled, so benchmarks and load tests must allow for it. You can watch compilation with -XX:+PrintCompilation.

Take quiz
Why does a Java service often run slower right after startup?
The OS has not yet allocated the whole heap
Bytecode is re-verified on every request
Hot code is still interpreted until the JIT compiles it
Garbage collection is disabled for the first minute
Which HotSpot compiler applies the most aggressive profile-guided optimizations?
C1
C2
javac
jlink

11. What is the purpose of the -Xms and -Xmx flags?

-Xms sets the initial heap size and -Xmx sets the maximum heap size. The JVM grows or shrinks the heap between those two values as needed.

java -Xms4g -Xmx4g -jar app.jar

Many production services set both to the same value. That avoids resize steps at runtime, which can trigger extra GCs and make behavior harder to predict.

Keep in mind that -Xmx limits only the Java heap, not the whole process. Metaspace, thread stacks (-Xss), the code cache, and direct buffers all use extra native memory, so leave headroom when sizing containers.

Take quiz
What does -Xmx control?
The maximum Java heap size
The maximum thread stack size
The total native memory the process may use
The maximum Metaspace size
Why do many production setups set -Xms equal to -Xmx?
To disable garbage collection
To avoid heap resizing at runtime
To shrink Metaspace
To make the JIT compile faster

12. What is a stop-the-world pause?

A stop-the-world (STW) pause is a moment when the JVM halts all application threads so it can do work that needs a stable view of the heap and thread stacks. Young collections, parts of G1 and Parallel old collections, and Full GC all do this.

Before a pause starts, every thread must reach a safepoint. The time it takes to get them there (time to safepoint) is part of the pause the user sees. GC is the main cause, but heap dumps, deoptimization, and class redefinition can also stop the world.

For a web service, a long pause shows up as a latency spike or a timeout. Parallel GC accepts longer pauses to maximize throughput, while ZGC and Shenandoah do most of their work concurrently to keep pauses very short. You can inspect pauses with -Xlog:gc and -Xlog:safepoint.

Take quiz
Why does the JVM bring threads to a safepoint?
To flush the code cache to disk
To give each thread a larger stack
So it can run work that needs a stable view of the heap and stacks
So the OS can swap the heap to disk
Which collectors keep pauses short by doing most work concurrently?
Serial and Parallel
Parallel only
Epsilon only
ZGC and Shenandoah

13. What is a memory leak in Java?

A Java memory leak happens when objects are still reachable but no longer needed, so the garbage collector cannot free them. Memory use climbs until the JVM slows down in constant GC or throws OutOfMemoryError.

The telltale sign in GC logs is a staircase: heap usage after a full GC keeps rising over hours or days.

Typical causes:

  • Static collections that only grow
  • Unbounded caches with no eviction
  • Listeners or callbacks that are never unregistered
  • ThreadLocal values left on pooled threads
  • Unclosed streams, statements, or connections
  • Class loader leaks after repeated redeploys
private static final List<byte[]> CACHE = new ArrayList<>();

void handle() {
    CACHE.add(new byte[1024]);   // added on every call, never removed
}

Take quiz
Which GC-log pattern most clearly suggests a leak?
Young GC pauses disappear
CPU usage drops to zero
Heap usage after full GC keeps rising over time
Metaspace shrinks steadily
Which is a classic cause of a Java memory leak?
Using final local variables
A static map that only ever grows
Short-lived local objects inside methods
Declaring methods as private

14. What is a heap dump?

A heap dump is a snapshot of every object on the Java heap at one moment: classes, instances, field values, and the references between them. It is usually saved as an .hprof file.

Ways to capture one:

jcmd <pid> GC.heap_dump /tmp/app.hprof
jmap -dump:live,format=b,file=/tmp/app.hprof <pid>
java -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/dumps -jar app.jar

Taking a dump pauses the application, and the file is roughly the size of the live heap. It also contains whatever was in memory, including passwords and tokens, so store and share it carefully.

Analyze it with Eclipse MAT, VisualVM, or the IntelliJ profiler to find leaks, oversized collections, and duplicated strings.

Take quiz
Which flag writes a heap dump automatically when the heap runs out?
-XX:+PrintGCDetails
-Xlog:gc*
-XX:+HeapDumpOnOutOfMemoryError
-XX:+UseStringDeduplication
What is a security concern with heap dump files?
They corrupt the class files of the application
They permanently disable the JIT compiler
They are automatically uploaded to the JDK vendor
They can contain passwords, tokens, and personal data held in memory

15. What is a thread dump?

A thread dump is a snapshot of every thread in the JVM with its state and stack trace. It shows what each thread was doing at that instant.

jstack <pid>
jcmd <pid> Thread.print
kill -3 <pid>      # prints to the JVM's stdout

Thread states you will see are RUNNABLE, BLOCKED, WAITING, and TIMED_WAITING. Take three to five dumps, a few seconds apart. One dump is a photo; several make a movie, and you can see which threads are genuinely stuck.

What to look for:

  • Many threads BLOCKED on the same monitor - lock contention
  • Threads sitting in the same frame across dumps - a hang or slow call
  • A "Found one Java-level deadlock" section
  • All pool threads waiting on a database or remote call

Virtual threads (JDK 21) are not in the plain dump; use jcmd <pid> Thread.dump_to_file -format=json file.json.

Take quiz
How many thread dumps should you usually take when diagnosing a hang or slowdown?
Several, spaced a few seconds apart
None; a heap dump is enough
Exactly one, right after startup
One per GC cycle, together with a heap dump
What does a large number of BLOCKED threads on the same monitor suggest?
A full GC in progress
Excessive JIT compilation
Lock contention
A Metaspace leak

16. What is JMH?

JMH (Java Microbenchmark Harness) is the OpenJDK tool for writing reliable microbenchmarks. It handles the things that make hand-written timing loops misleading: JIT warm-up, dead-code elimination, constant folding, and profile pollution between runs.

@State(Scope.Thread)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Warmup(iterations = 3)
@Measurement(iterations = 5)
@Fork(2)
public class ConcatBench {
    String a = "foo", b = "bar";          // non-final on purpose

    @Benchmark
    public String plus() { return a + b; }   // returned value is consumed by JMH
}

@Warmup lets the JIT settle, @Fork runs in fresh JVMs, and returning the result (or using Blackhole) stops the JIT from deleting the work.

Common modes are Throughput, AverageTime, SampleTime (percentiles), and SingleShotTime (cold start). Run it from the Maven or Gradle plugin, not from the IDE's normal run button.

Use JMH to compare small code alternatives. It does not tell you how a whole application behaves under load.

Take quiz
Why should a JMH benchmark method return its result or use a Blackhole?
To run the benchmark in a separate process
To write the value into the GC log
So the JIT cannot remove the work as dead code
To increase the number of forks
What does @Fork do in JMH?
Splits the benchmark across threads automatically
Creates a branch of the git repository
Duplicates the heap before each run
Runs the benchmark in fresh JVM processes to avoid profile pollution

17. Define Amdahl's Law in the context of performance tuning?

Amdahl's Law says that the speedup you get from parallelizing a task is limited by the part that must still run serially.

Speedup = 1 / ((1 - p) + p / n)

p = parallel fraction of the work, n = number of processors

Example: if 90% of a job can run in parallel (p = 0.9), 8 cores give about 1 / (0.1 + 0.1125) = 4.7x. Even with unlimited cores the ceiling is 1 / 0.1 = 10x.

In Java terms, the serial part is often a shared lock, a single-threaded I/O stage, or one overloaded database. Before adding threads or cores, find and shrink those serial sections. Real systems also pay coordination costs, so the practical limit is lower than the formula suggests.

Take quiz
If 20% of a task is strictly serial, what is the maximum speedup from unlimited cores?
5x
2x
Unlimited
20x
According to Amdahl's Law, what limits parallel speedup?
The JIT compilation tier
The portion of the work that must run serially
The size of the young generation
The number of loaded classes

18. What is Metaspace?

Metaspace is the area of native memory where the JVM stores class metadata: class structures, method data, and constant pools. It replaced PermGen in Java 8.

It grows automatically and, by default, is limited only by available native memory. Two flags matter:

  • -XX:MaxMetaspaceSize - hard cap; exceeding it throws OutOfMemoryError: Metaspace
  • -XX:MetaspaceSize - threshold that triggers the first GC for class unloading

Metaspace usually fills up because of class loader leaks (repeated redeploys in an app server) or heavy runtime class generation from proxies and bytecode libraries. You can check usage with jcmd <pid> VM.metaspace or jstat -gcmetacapacity <pid>.

Take quiz
Which memory area did Metaspace replace in Java 8?
PermGen
The thread stack area
The survivor spaces
The code cache
Where is Metaspace allocated?
Inside the old generation
Inside Eden
On each thread's stack
In native memory outside the Java heap

19. What is the difference between sampling and instrumentation profiling?

A sampling profiler periodically captures stack traces and infers hot spots statistically. An instrumentation profiler rewrites bytecode to record every method entry and exit, so it counts everything but costs far more.

Aspect Sampling Instrumentation
How it works Takes stack snapshots every few milliseconds Inserts timing code at method entry and exit
Overhead Low and predictable High; grows with call frequency
Accuracy Statistical; may miss very short methods Exact call counts
Distortion Minimal Can distort timings and block inlining
Typical use Production, first investigation Targeted questions such as how often a method is called

Start with sampling (JFR, async-profiler). Switch to instrumentation only when you need exact invocation counts, and limit it to a few classes. JProfiler and YourKit offer both modes.

Take quiz
Which approach gives exact method invocation counts?
Instrumentation profiling
GC log analysis
Sampling profiling
Heap dump analysis
Why is sampling preferred for profiling production systems?
It requires a special debug build
It has low, predictable overhead
It disables the JIT to stay accurate
It records every call exactly

20. Why is safepoint bias a problem for some Java profilers?

Some profilers can only take a stack sample when a thread is at a safepoint. Samples therefore pile up at safepoint polls, such as method returns and loop back-edges, instead of at the code that actually burns CPU. The profile then blames the wrong method.

A tight loop with no poll inside can be nearly invisible, while a small method nearby that has a poll shows up as the "hot" one. You end up optimizing code that was not the problem.

Profilers built on jstack-style or JVMTI safepoint sampling have this bias. async-profiler avoids it by using AsyncGetCallTrace with OS-level timers, and JFR's sampler is not safepoint-based either.

For accurate line-level attribution, add -XX:+UnlockDiagnosticVMOptions -XX:+DebugNonSafepoints when profiling.

Take quiz
What is the effect of safepoint bias?
Only GC threads are ever sampled
Profiler overhead drops to zero
Samples cluster at safepoint polls rather than at the true hot code
Samples are taken too rarely to display anything
Which profiler avoids safepoint bias?
A tool that only reads GC logs
A tool that repeatedly runs jstack
async-profiler
Any tool that calls System.gc() before sampling

21. How do you read a flame graph?

In a flame graph each box is a method, and its width is the share of samples that included it. The x-axis is not time; frames are just sorted so identical stacks merge. The y-axis is stack depth, with the entry point at the bottom and the method on CPU at the top.

Read it like this:

  1. Look for the widest frames at the top of stacks. Those are where time is actually spent.
  2. Follow a wide frame downwards to see who called it.
  3. Hover or click a frame to see its exact percentage of samples.
  4. Use search to highlight a package or class and see how much of the total it covers.

A tall, narrow tower is just deep recursion or framework layers and is rarely the problem. A wide plateau is.

asprof -d 30 -e cpu -f flame.html <pid>     # CPU
asprof -d 30 -e alloc -f alloc.html <pid>   # allocations

Switching the event to alloc, lock, or wall gives the same view for memory, contention, or elapsed time.

Take quiz
What does the width of a frame in a flame graph represent?
The share of samples that include that frame
Elapsed time on a left-to-right timeline
The number of threads running that method
The bytecode size of the method
Where should you look first for CPU hot spots in a flame graph?
At the tallest tower regardless of width
At wide frames near the top of the stacks
At narrow frames at the very bottom
Only at the leftmost frame

22. How does tiered compilation work in HotSpot?

Tiered compilation lets HotSpot start fast with the interpreter, then move hot methods through the C1 compiler and finally the C2 compiler. You get quick startup from C1 and top speed from C2.

Tier Executor Role
0 Interpreter Runs bytecode and collects counters
1-3 C1 Quick compile; tier 3 adds full profiling
4 C2 Aggressive optimization using the profile

flowchart LR
  A["Tier 0: interpreter"] --> B["Tier 3: C1 with full profiling"]
  B --> C["Tier 4: C2 optimized code"]
  C -- assumption fails --> A

A method is queued for compilation when its invocation and loop back-edge counters pass a threshold. Background compiler threads do the work, so the application keeps running. Long-running loops use on-stack replacement (OSR) to switch to compiled code mid-execution.

-XX:TieredStopAtLevel=1 limits the JVM to C1. That helps short-lived tools and CLIs start faster but lowers peak throughput.

Take quiz
What does tier 3 (C1 with full profiling) provide?
Verification of bytecode before loading
A switch that disables garbage collection
Profile data that C2 later uses for aggressive optimization
A native image of the application
What does -XX:TieredStopAtLevel=1 do?
Disables the interpreter
Forces C2 to compile every method on its first call
Stops the JVM after one GC cycle
Limits compilation to C1, trading peak speed for faster startup

23. How does the G1 garbage collector work?

G1 divides the heap into equal-sized regions (1 to 32 MB) instead of two big contiguous generations. Each region plays a role at a given time: eden, survivor, old, or humongous. G1 then collects the regions that give the most garbage back for the pause time allowed.

flowchart TD
  A["Young GC: evacuate eden and survivors"] --> B{Heap occupancy above IHOP?}
  B -- No --> A
  B -- Yes --> C["Concurrent marking cycle"]
  C --> D["Mixed GCs: young plus the most garbage-rich old regions"]
  D --> A
  D -. cannot keep up .-> E["Full GC fallback"]
  1. Young collection - stop-the-world; live objects are copied out of eden and survivor regions in parallel.
  2. Concurrent marking - starts when occupancy crosses the initiating threshold (-XX:InitiatingHeapOccupancyPercent, 45% by default and adaptive).
  3. Mixed collections - clean young regions plus old regions with the most garbage, as many as fit the pause goal.
  4. Pause goal - -XX:MaxGCPauseMillis, 200 ms by default.

Objects at least half a region in size are humongous and take contiguous regions, which can cause fragmentation. If G1 runs out of space to evacuate into, it logs to-space exhausted and falls back to a Full GC.

Take quiz
What is G1's default pause-time goal?
2 seconds
1 ms
20 ms
200 ms
What happens when heap occupancy crosses the IHOP threshold in G1?
The region size is doubled
A concurrent marking cycle starts
Mixed collections are disabled permanently
A Full GC is triggered immediately

24. When would you choose ZGC over G1?

Choose ZGC when pause time, not raw throughput, is your main constraint: strict tail-latency targets, or very large heaps where G1 pauses grow beyond your SLO.

ZGC does marking, relocation, and reference processing concurrently, using colored pointers and load barriers. Pauses typically stay well below a millisecond and do not grow with heap size, and heaps up to 16 TB are supported.

Aspect G1 ZGC
Pause time Goal-based, often tens to hundreds of ms Sub-millisecond, independent of heap size
Heap size Small to large Medium to very large
CPU overhead Lower Higher (barriers, concurrent threads)
Needs headroom Some More; fast allocation can cause allocation stalls
Best for General services, throughput focus Latency-critical services, big heaps

Generational ZGC arrived in JDK 21 and improves throughput and footprint. Stay with G1 when the heap is small, CPUs are scarce, or throughput matters more than the last few milliseconds of tail latency.

Take quiz
What lets ZGC keep pauses short regardless of heap size?
A single huge eden that is never collected
Swapping the heap to disk during GC
Concurrent marking and relocation using colored pointers and load barriers
Skipping the marking phase entirely
When is G1 likely a better choice than ZGC?
A latency-critical API with plenty of spare cores
A 2 TB heap with a 1 ms pause SLO
An application that never allocates objects
A small-heap, CPU-constrained service where throughput matters most

25. What is the difference between Parallel GC and G1 GC?

Parallel GC maximizes throughput by using many threads, but it stops the world for every young and old collection. G1 aims for predictable pauses by working region by region and doing part of its work concurrently.

Aspect Parallel GC G1 GC
Primary goal Maximum throughput Balanced throughput with a pause target
Heap layout Contiguous young and old generations Equal-sized regions
Old-gen cleanup Full stop-the-world collection Concurrent marking, then mixed collections
Pause behavior Grows with old generation size Tuned towards MaxGCPauseMillis
Overhead Lower barrier and memory cost Write barriers and remembered sets cost CPU and memory

Pick Parallel for batch jobs and offline processing where total completion time matters and a long pause is acceptable. Pick G1 for interactive services where a multi-second pause would break SLAs.

Take quiz
Which collector stops all application threads for both young and old collections?
Parallel GC
Shenandoah
ZGC
G1 GC
Why does G1 usually give shorter worst-case pauses than Parallel on large heaps?
It skips young collections
It always uses a smaller heap
It marks concurrently and collects old regions incrementally
It never moves objects

26. How do you enable and read GC logs?

On JDK 9 and later, use unified logging. On JDK 8, use the older -XX:+PrintGCDetails family.

# JDK 9+
-Xlog:gc*:file=gc.log:time,uptime,level,tags:filecount=5,filesize=20m

# JDK 8
-XX:+PrintGCDetails -XX:+PrintGCDateStamps -Xloggc:gc.log

A typical G1 line looks like this:

[2.345s][info][gc] GC(5) Pause Young (Normal) (G1 Evacuation Pause) 512M->128M(1024M) 8.532ms

512M->128M(1024M) means heap used before, heap used after, and total heap size; the last value is the pause duration.

What to check: pause length and frequency, the heap size after each GC (a rising trend means a leak), promotion into old, Pause Full entries, to-space exhausted, and humongous allocations. Tools like GCeasy and GCViewer chart this. The logging is cheap enough to leave on in production, and rotating files (filecount, filesize) keep disk use bounded.

Take quiz
In the entry 512M->128M(1024M) 8.5ms, what does 128M represent?
The survivor space size
Memory freed by the collection
Heap used after the collection
Reserved Metaspace
Which flag enables GC logging through unified logging on JDK 9+?
-verbose:heap
-Xgclog
-XX:+LogGC
-Xlog:gc*

27. Why does a high allocation rate hurt Java performance?

Allocating an object is cheap, but every byte you allocate has to be handled later. A high allocation rate fills eden quickly, so young GCs run more often and objects get less time to die before a collection.

Example: with a 500 MB eden and 1 GB/s of allocation, a young GC fires roughly every 0.5 seconds.

The knock-on effects:

  • Objects still in use at collection time are copied or promoted early into old, which later forces mixed or full GCs
  • More CPU goes to GC threads instead of your code
  • Fresh memory churn pollutes CPU caches and uses memory bandwidth

To find the source, use JFR allocation events or async-profiler -e alloc. Typical fixes are reusing buffers, avoiding boxing, skipping needless intermediate collections and strings, precompiling regex Pattern objects, and not building log messages that are discarded.

Take quiz
With a 500 MB eden and 1 GB/s allocation, about how often does a young GC occur?
Roughly every 0.5 seconds
Only when the old generation is full
Roughly every 5 seconds
Roughly once a minute
Which approach shows where objects are being allocated?
javap on the main class
async-profiler with the alloc event
jps -v
jstack with the -l option

28. How does escape analysis reduce object allocation?

Escape analysis is a C2 optimization that checks whether an object can be seen outside the method (or thread) that created it. If it cannot, the JVM may skip the heap allocation entirely through scalar replacement: the object's fields become plain local values in registers.

double dist(double x1, double y1, double x2, double y2) {
    Point d = new Point(x2 - x1, y2 - y1);   // may never be allocated
    return Math.sqrt(d.x * d.x + d.y * d.y);
}

A related win is lock elision: a synchronized block on an object that never escapes the thread can be removed.

The object must not escape. Storing it in a field, returning it, adding it to a collection, or passing it to a method that is not inlined all defeat the optimization. HotSpot does not allocate whole objects on the stack; it replaces them with scalars. The feature is on by default (-XX:+DoEscapeAnalysis), but verify with an allocation profile rather than assuming it applied.

Take quiz
What may HotSpot do with an object that escape analysis proves does not escape?
Force a GC to free it at once
Move it to the old generation immediately
Scalar-replace it so no heap allocation happens
Serialize it to disk
Which usage typically makes an object escape?
Reading its fields inside the same method
Declaring the reference final
Using it only in local arithmetic
Storing it in a field of a shared object

29. Why is autoboxing a performance concern in Java?

Autoboxing silently converts a primitive such as int into a wrapper object such as Integer. Outside the small cache (values -128 to 127) each conversion allocates a new object, adding GC pressure, extra memory, and pointer-chasing.

Long sum = 0L;
for (long i = 0; i < 1_000_000; i++) {
    sum += i;          // unbox, add, box into a new Long every iteration
}

Memory cost matters too: an int takes 4 bytes, while an Integer takes around 16 bytes plus the reference that points to it. A List<Integer> of a million numbers is several times bigger than an int[].

Fixes: use primitives in hot loops, use IntStream and LongStream instead of boxed streams, and consider primitive collection libraries such as fastutil or Eclipse Collections. Also avoid comparing boxed values with ==.

Take quiz
Why is `Long sum = 0L; sum += i;` slow inside a loop?
Each addition unboxes and then allocates a new Long
Each iteration forces a safepoint
The variable is stored in Metaspace
Long values are never compiled by the JIT
What is a performance-friendly alternative to List<Integer> for large numeric data?
A LinkedList<Integer>
A primitive int[] or a primitive collection library
List<Number>
A Vector<Integer>

30. Why should you set the initial capacity of a HashMap or ArrayList?

Because growing is not free. A HashMap starts with 16 buckets and a 0.75 load factor; when it passes the threshold it doubles the table and rehashes every entry. An ArrayList grows by about 1.5x and copies its whole array each time.

If you roughly know the final size, presizing avoids repeated resizes, copying, and the temporary garbage they create.

// ArrayList
List<String> names = new ArrayList<>(10_000);

// HashMap for n expected entries
Map<String, User> byId = new HashMap<>((int) (n / 0.75f) + 1);

// Java 19+
Map<String, User> byId2 = HashMap.newHashMap(n);

Presizing matters most for large collections built in bulk, such as loading a result set or parsing a big file, where a single missed resize can copy millions of entries.

Do not overdo it. A huge table for a map that stays small wastes memory, and for small collections the saving is not measurable.

Take quiz
In Java 19+, which method creates a HashMap sized for n entries without manual load-factor math?
HashMap.ofSize(n)
Map.sized(n)
HashMap.newHashMap(n)
HashMap.withCapacity(n)
What happens when a HashMap grows past capacity times load factor?
The table doubles in size and entries are rehashed
A Full GC is forced
The map turns into a LinkedList
The oldest entries are evicted

31. How do you size a thread pool?

Size it by the kind of work. CPU-bound tasks need roughly one thread per core (cores or cores + 1); extra threads only add context switching. I/O-bound tasks can use more, because threads spend most of their time waiting.

A common starting formula, from Java Concurrency in Practice:

threads = cores x (1 + wait time / compute time)

Example: 8 cores, tasks that wait 90 ms and compute 10 ms gives 8 x (1 + 9) = 80 threads.

Then check the limits around the pool:

  • Use a bounded queue and a rejection policy. An unbounded queue hides overload and can exhaust memory.
  • Do not exceed downstream capacity. 80 threads sharing a 20-connection database pool just wait in line.
  • Use separate pools for CPU work and blocking work.
  • Treat the formula as a starting point and confirm with a load test.
Take quiz
8 cores, tasks wait 90 ms and compute 10 ms. What pool size does the Goetz formula give?
80
720
8
16
Why should a thread pool's work queue be bounded?
Bounded queues make each task run faster
An unbounded queue hides overload and can exhaust memory
It lets tasks bypass the pool
The JVM refuses to start otherwise

32. What is lock contention and how do you detect it?

Lock contention happens when many threads compete for the same lock, so most of them wait. The symptom is distinctive: low CPU usage but high latency, and throughput that stops improving when you add cores.

Ways to detect it:

  • Thread dumps with many threads BLOCKED, all waiting to lock the same monitor address
  • JFR monitor events such as jdk.JavaMonitorEnter
  • async-profiler -e lock to rank locks by wait time
  • High context-switch counts in vmstat or pidstat

Common fixes: shorten the critical section, split one lock into several (lock striping, as ConcurrentHashMap does), use LongAdder for hot counters, use ReadWriteLock or StampedLock for read-heavy data, or avoid shared mutable state.

// Before: remote call holds the lock
synchronized (this) { String r = callRemote(); cache.put(k, r); }

// After: lock only the shared update
String r = callRemote();
synchronized (this) { cache.put(k, r); }

Take quiz
Which JFR event points to monitor contention?
jdk.GarbageCollection
jdk.ClassLoad
jdk.JavaMonitorEnter (Java Monitor Blocked)
jdk.CompilerPhase
Which change most directly reduces contention on a hot shared counter?
Adding more GC threads
Making the counter volatile and keeping the lock
Increasing the heap size
Using LongAdder instead of a single synchronized counter

33. How do virtual threads change performance tuning for blocking workloads?

Virtual threads (final in JDK 21) are lightweight threads scheduled by the JVM onto a small set of carrier threads. When one blocks on I/O or a ReentrantLock, it unmounts and the carrier runs something else. That lets a thread-per-request style handle hundreds of thousands of concurrent waits.

They help I/O-bound, highly concurrent work. They do nothing for CPU-bound code, which is still limited by cores.

try (var ex = Executors.newVirtualThreadPerTaskExecutor()) {
    for (var url : urls) ex.submit(() -> fetch(url));
}

What changes in tuning:

  • Do not pool them. Create one per task.
  • Limit scarce resources with a Semaphore or the connection pool size, not with a small thread pool.
  • Watch for pinning. Blocking inside synchronized pins the carrier on JDK 21-23; JDK 24 largely removes this. Detect it with the jdk.VirtualThreadPinned JFR event.
  • Be careful with heavy ThreadLocal use, since there can be a huge number of threads.
Take quiz
Which workload benefits most from virtual threads?
A single-threaded batch parser
Many concurrent tasks that mostly block on I/O
A CPU-bound image filter
A tight numeric loop using all cores
How should you limit concurrent calls to a scarce database when using virtual threads?
Set -Xss to 1 KB
Use a Semaphore or the pool limit, not a small thread pool
Disable unmounting for blocking calls
Pool the virtual threads in a fixed-size executor

34. Why is a parallel stream not always faster?

A parallel stream has to split the data, hand pieces to the common ForkJoinPool, and merge the results. That overhead only pays off when there is enough work per element.

It tends to win when:

  • There are many elements and each does real CPU work
  • The source splits cheaply (ArrayList, arrays, IntStream.range)
  • Operations are stateless and associative

It tends to lose when:

  • The data set is small
  • The source splits poorly (LinkedList, Stream.iterate)
  • The lambda does blocking I/O, which starves the common pool that the whole JVM shares
  • Ordering matters (limit, findFirst, sorted)
  • Lambdas mutate shared state and need synchronization

The default parallelism is cores minus one. Benchmark with JMH on realistic data before switching. For blocking work, a dedicated executor or virtual threads is a better fit.

Take quiz
Which stream source splits well for parallel processing?
A LinkedList
A stream of lines from a BufferedReader
An ArrayList or an array
Stream.iterate(...)
Why is blocking I/O inside parallelStream() risky?
It forces a Full GC
parallelStream cannot call methods
Worker threads cannot open files
It can starve the shared common ForkJoinPool used across the JVM

35. How does connection pooling improve database performance?

Opening a database connection is expensive: a TCP handshake, often TLS, authentication, and session setup, which together can take milliseconds to tens of milliseconds. A pool keeps connections open and lends them out in microseconds, then takes them back.

A pool also acts as a concurrency limit, so a traffic spike queues in the application instead of overwhelming the database.

HikariCP is the default in Spring Boot. Points to know:

  • maximumPoolSize defaults to 10, and smaller pools are often faster than large ones. A common starting rule from the PostgreSQL community is (cores x 2) + effective spindles.
  • connectionTimeout controls how long a thread waits for a connection.
  • leakDetectionThreshold logs connections held too long.

If threads sit in getConnection() and requests time out, the pool is exhausted. The cure is usually shorter transactions or fixing leaks, not just a bigger pool. Never hold a connection while calling a remote service.

Take quiz
What is HikariCP's default maximumPoolSize?
10
50
Unlimited
1
Threads waiting inside getConnection() and timeouts most likely indicate:
Metaspace is too small
The young generation is too large
Pool exhaustion from long transactions or leaked connections
The JIT deoptimized hot code

36. What is the N+1 query problem and how do you fix it?

The N+1 problem occurs when loading a list triggers one query for the parents and then one extra query per parent for a lazy association. Loading 100 orders and touching each order's items runs 101 queries instead of one or two.

List<Order> orders = em.createQuery("select o from Order o", Order.class).getResultList();
int total = 0;
for (Order o : orders) {
    total += o.getItems().size();   // lazy load: one extra query per order
}

Detect it by logging SQL, enabling hibernate.generate_statistics, or using a proxy like datasource-proxy or p6spy to count queries per request.

Fixes:

  • join fetch or an @EntityGraph to load children with the parents
  • Batch fetching (@BatchSize or hibernate.default_batch_fetch_size), which loads children with IN lists
  • DTO projections that select only the needed columns

Watch the side effects: join fetch on several collections can produce a cartesian product, and combining it with pagination makes Hibernate page in memory.

Take quiz
One query loads 100 orders, then each order's items are loaded lazily. How many queries run?
100
200
101
2
Which approach loads related items with far fewer queries?
Adding more application threads
Increasing the connection pool size
Calling em.clear() inside the loop
JOIN FETCH or an entity graph

37. How do you troubleshoot high CPU usage in a Java process?

Find the busiest thread, map it to a Java stack, then decide whether the cost is application code, GC, or the JIT.

  1. Find the process with top, then list its threads: top -H -p <pid>. Note the IDs of the busiest threads.
  2. Convert a thread ID to hex: printf '%x\n' 12345.
  3. Take a thread dump with jstack <pid> and find the entry with the matching nid=0x.... Take several dumps to confirm.
  4. Read the stack. An application thread in a loop, regex, or serializer points to code. Threads named GC Thread or C2 CompilerThread point elsewhere.
  5. For GC threads, read the GC log for frequent collections or a leak. For compiler threads, check warm-up and code cache. For application threads, confirm with async-profiler -e cpu or JFR.
top -H -p 4321
printf '%x\n' 4399        # 112f
jstack 4321 | grep -A 15 'nid=0x112f'

Frequent culprits are tight or accidental infinite loops, catastrophic regex backtracking, excessive serialization or logging, busy-wait polling, and GC thrash caused by a leak.

Take quiz
In jstack output, thread IDs taken from top -H must be converted to which form?
Hexadecimal, to match the nid value
Base64
Octal
Binary
If top -H shows GC threads using most of the CPU, what is the sensible next step?
Increase the thread stack size
Check GC logs for frequent collections or a leak
Recompile the application with optimization flags
Disable the JIT compiler

38. How do you troubleshoot an OutOfMemoryError?

Start with the text after OutOfMemoryError:, because it tells you which memory area ran out.

Message Meaning First action
Java heap space Heap is full of live objects Analyze a heap dump; find the leak or raise -Xmx
GC overhead limit exceeded Almost all time is spent in GC with little reclaimed Same as above, plus read the GC log
Metaspace Class metadata exhausted Look for class loader leaks or runtime class generation
unable to create native thread OS or native memory thread limit Count threads; check ulimit -u, -Xss, container limits
Direct buffer memory NIO direct buffers exhausted Check -XX:MaxDirectMemorySize and unreleased buffers
Requested array size exceeds VM limit Array too large Fix the code that computes the size

Make sure the evidence exists before the next failure:

-XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/dumps -XX:+ExitOnOutOfMemoryError

In containers, exit code 137 with no Java error usually means the kernel OOM killer ended the process because total memory (heap plus native) passed the limit. That is not a Java OutOfMemoryError, so look at non-heap usage with NMT and RSS.

Take quiz
A container exits with code 137 and no OutOfMemoryError appears in the logs. What is the likely cause?
A thread dump was requested
The Metaspace limit was reached
The GC overhead limit was exceeded
The kernel OOM killer stopped it for exceeding the container memory limit
Which message points to a native thread or OS limit problem?
Metaspace
Java heap space
GC overhead limit exceeded
unable to create native thread

39. How do you find a memory leak using a heap dump?

First confirm it is a real leak: in the GC log, heap used after full GCs should be trending upwards. Then follow the references to find what keeps the objects alive.

  1. Capture a dump, ideally two a few minutes apart: jcmd <pid> GC.heap_dump /tmp/h1.hprof.
  2. Open it in Eclipse MAT and run the Leak Suspects report for a quick lead.
  3. Check the histogram for classes with surprisingly many instances.
  4. Open the dominator tree sorted by retained heap. Retained heap is what would be freed if the object were collected; shallow heap is just the object itself.
  5. On a suspect, choose Path to GC Roots and exclude weak and soft references. The path shows exactly who holds it.
  6. Compare the two dumps to see which classes grew.

Frequent roots are a static map, a listener registry, a ThreadLocal on pooled threads, or a class loader. Fix the holding reference, not the symptom.

For a quick check without a dump, run jcmd <pid> GC.class_histogram twice and compare the counts.

Take quiz
In Eclipse MAT, which measure shows the memory that would be freed if an object were collected?
Retained heap
Native size
Allocation rate
Shallow heap
Which MAT feature explains why an object is still reachable?
Histogram sorted by class name
Path to GC Roots, excluding weak and soft references
The OQL syntax reference
The thread overview page

40. Why do hand-written microbenchmarks give misleading results?

Because the JVM optimizes while it runs, a naive timing loop often measures the JIT, not your code.

  • Warm-up: early iterations are interpreted, and compilation can happen in the middle of your measurement.
  • Dead-code elimination: if the result is unused, the JIT may delete the whole computation.
  • Constant folding: constant inputs let the compiler compute the answer at compile time.
  • Loop optimizations: trivial loops get unrolled, hoisted, or removed.
  • Profile pollution: running several benchmarks in one JVM specializes the JIT for whichever ran first.
  • Noise: GC, CPU frequency scaling, and other processes.
long t = System.nanoTime();
for (int i = 0; i < 1_000_000; i++) { Math.sqrt(i); }   // result unused
System.out.println(System.nanoTime() - t);               // may report almost nothing

JMH counters these with warm-up iterations, forked JVMs, Blackhole, non-final @State fields, and repeated measurement with statistics. Even then, a microbenchmark win must be confirmed at application level with a profiler or load test.

Take quiz
Why can the loop calling Math.sqrt(i) with an unused result look impossibly fast?
Math.sqrt results are cached on disk
The loop is automatically parallelized
The JIT may remove it as dead code
nanoTime stops counting during GC
What does Blackhole.consume() in JMH prevent?
Class loading of the benchmark
Thread migration between cores
Garbage collection of the benchmark class
Dead-code elimination of the computed value

41. Explain the lifecycle of an object in a generational garbage collector?

An object is born in eden, copied between survivor spaces while it keeps surviving, and is finally promoted to the old generation if it lives long enough.

flowchart TD
  A["new Object allocated in Eden via TLAB"] --> B["Eden fills: minor GC"]
  B --> C{Still reachable?}
  C -- No --> D["Left behind, space reclaimed"]
  C -- Yes --> E["Copied to survivor space, age = 1"]
  E --> F["Next minor GC: copied to other survivor, age + 1"]
  F --> G{Age at threshold or survivor full?}
  G -- No --> F
  G -- Yes --> H["Promoted to old generation"]
  H --> I["Collected by major, mixed, or full GC"]
  1. The object is allocated in eden, usually inside the thread's TLAB.
  2. At the next minor GC, live objects are copied to a survivor space with age 1. Dead ones are simply not copied.
  3. Each later minor GC copies survivors to the other survivor space and increases their age.
  4. At the tenuring threshold (-XX:MaxTenuringThreshold, at most 15, adjusted adaptively), or when a survivor space overflows, the object is promoted to old.
  5. Very large objects may skip this path: they go straight to old, or to humongous regions in G1.

Early promotion is what hurts. If survivor space is too small or allocation is too fast, short-lived data reaches old and later triggers expensive collections. Check the age distribution with -Xlog:gc+age=trace.

Take quiz
What causes an object to be promoted to the old generation?
Reaching the tenuring threshold, or a survivor space overflow
Surviving one Full GC
Being referenced by a static field only
Being larger than 1 KB
Which log tag shows the tenuring age distribution?
safepoint
gc+age=trace
class+load
gc+heap=off

42. Explain the internal working of TLAB allocation?

A TLAB (thread-local allocation buffer) is a private slice of eden handed to one thread. The thread allocates by moving a pointer forward inside its own slice, so there is no lock and no atomic operation. In JIT-compiled code it is only a few instructions.

flowchart TD
  A["new Object"] --> B{Fits in current TLAB?}
  B -- Yes --> C["Bump pointer, return object"]
  B -- No --> D{Object large or TLAB nearly full?}
  D -- Refill --> E["Retire TLAB, take a new one from eden"]
  E --> C
  D -- Large object --> F["Allocate directly in eden with synchronization"]

When a TLAB cannot fit the next object, the JVM either retires it and fetches a fresh one, or allocates that object outside the TLAB in the shared eden, which is the slower path. The unused tail of a retired TLAB is filled with a dummy object so the heap stays parseable. TLAB size adapts to each thread's allocation rate.

Flags and tools: -XX:+UseTLAB (default), -XX:TLABSize, -XX:+ResizeTLAB, -Xlog:gc+tlab=trace, and the JFR events jdk.ObjectAllocationInNewTLAB and jdk.ObjectAllocationOutsideTLAB. Frequent outside-TLAB events usually mean you are allocating many large arrays or buffers.

Take quiz
Why does TLAB allocation need no locking?
Allocation is deferred until the next safepoint
Objects are allocated on the thread stack instead
Each thread bumps a pointer inside its own private chunk of eden
All threads are paused during every allocation
Which JFR event indicates an allocation that bypassed the TLAB?
jdk.ThreadPark
jdk.GCHeapSummary
jdk.ClassLoadingStatistics
jdk.ObjectAllocationOutsideTLAB

43. What is false sharing and how do you avoid it?

False sharing happens when two threads write to different variables that sit on the same cache line (64 bytes on most x86 CPUs). Each write invalidates the other core's copy of the line, so it bounces between cores even though the threads share no data logically. Throughput can drop several times.

class Counters {
    volatile long a;   // written by thread 1
    volatile long b;   // written by thread 2, probably on the same cache line as a
}

Ways to avoid it:

  • @jdk.internal.vm.annotation.Contended pads the field; for application classes it needs -XX:-RestrictContended
  • Keep per-thread state per thread, and combine it only when needed
  • Use LongAdder, whose internal cells are already padded
  • Manual padding fields, which is fragile because the JVM may reorder fields

It is hard to spot: scaling flattens as you add threads while there is no lock contention. On Linux, perf c2c reports cache-line contention, and a JMH test with and without padding confirms the diagnosis.

Take quiz
False sharing occurs when:
Different threads write different variables on the same cache line
Two threads synchronize on the same lock object
Two threads read the same immutable object
A thread copies a field to its own stack
Which JDK class keeps its internal cells padded to avoid false sharing?
ArrayList
LongAdder
StringBuilder
Optional

44. How can you reduce GC pause times in G1?

Read the GC log first to see which pause type and phase is long, then adjust one setting at a time.

  1. Set a realistic pause goal. -XX:MaxGCPauseMillis too low makes young generation smaller and GC more frequent, which costs throughput.
  2. Do not set -Xmn or -XX:NewSize. A fixed young size disables G1's adaptive sizing towards the pause goal.
  3. Avoid humongous allocations (objects at least half a region). Raise -XX:G1HeapRegionSize or split large arrays and buffers.
  4. Start marking earlier if you see to-space exhausted or Full GCs: lower -XX:InitiatingHeapOccupancyPercent, raise -XX:G1ReservePercent, or give the JVM more heap.
  5. Cut allocation and promotion so there is less to copy per pause.
  6. Avoid explicit System.gc() with -XX:+DisableExplicitGC or -XX:+ExplicitGCInvokesConcurrent.
  7. Pre-touch memory with -XX:+AlwaysPreTouch to avoid page-commit stalls during the run.

Add -XX:ConcGCThreads only if spare CPU exists. If pauses still miss the SLO on a very large heap, that is the moment to evaluate ZGC.

Take quiz
Why should you avoid setting -Xmn when using G1?
It turns off concurrent marking for good
G1 does not recognize the flag
A fixed young size disables adaptive sizing towards the pause goal
It switches the JVM to Serial GC
A to-space exhausted message in the G1 log usually suggests:
Metaspace is full
Too many threads were created
The code cache needs cleaning
Marking started too late or too few free regions were left to evacuate into

45. What happens when the JIT compiler deoptimizes code?

The JIT compiles optimistically. It assumes that an interface has one implementation, that a branch is never taken, that a call site sees one type, or that a value is not null. Compiled code carries guards for these assumptions (uncommon traps).

When a guard fails, the JVM deoptimizes: the thread's compiled frame is converted back into an interpreter frame and execution continues in the interpreter. The compiled method is marked made not entrant, counters are reset, and the method is recompiled later using the new profile.

Typical triggers:

  • Loading a new subclass that breaks a class-hierarchy assumption
  • An unexpected type, null, or branch direction showing up for the first time
  • Class redefinition

A few deoptimizations are normal. Repeated ones cause latency dips, usually seen when traffic changes shape after warm-up. Look for made not entrant in -XX:+PrintCompilation, the jdk.Deoptimization JFR event, or -Xlog:deoptimization=debug.

To limit it, warm up with realistic traffic variety, keep hot call sites from becoming megamorphic, and avoid loading new classes into hot paths late.

Take quiz
What does 'made not entrant' in PrintCompilation indicate?
The compiled code was invalidated and new calls will not enter it
The method was deleted from the source
The method was inlined into every caller permanently
The JIT crashed while compiling the method
Which event can trigger deoptimization?
Writing a line to a log file
Returning normally from a method
Calling System.nanoTime()
Loading a new subclass that breaks an assumption in compiled code

46. How do you tune the JVM for containers like Docker and Kubernetes?

Modern JVMs (JDK 8u191+ and 10+) read cgroup limits, but their defaults are conservative and need review.

  • Heap size: default MaxRAMPercentage is 25%, which usually wastes memory. Set -XX:MaxRAMPercentage=60 to 75, or an explicit -Xmx. Leave room for Metaspace, code cache, thread stacks, direct buffers, and GC structures.
  • Collector choice: a container under about 2 CPUs or 1.8 GB is treated as non-server class, so the JVM selects SerialGC. Set G1 or Parallel explicitly if you want them.
  • CPU: availableProcessors() follows the CPU limit, so pool sizes and GC threads follow it too. A tight CFS quota causes throttling pauses. Use -XX:ActiveProcessorCount to override if needed.
  • OOMKilled (exit 137): total process memory, not just heap, exceeded the limit. Track RSS and use NMT.
java -XX:MaxRAMPercentage=70 -XX:+UseG1GC -XX:+ExitOnOutOfMemoryError -jar app.jar

Verify the effective values with java -XX:+PrintFlagsFinal -version inside the actual container, because the node and the container can report very different resources.

Take quiz
With no -Xmx set, about how much of container memory does the JVM use for the max heap?
50% of the node memory
A fixed 1 GB
25%
100%
Why do containers with under about 2 CPUs and 1.8 GB often get SerialGC by default?
Kubernetes forbids parallel threads
G1 cannot run inside Docker
SerialGC is always faster in containers
The JVM classifies them as non-server-class machines

47. How can you optimize JVM startup time?

Start by finding where the time goes (class loading, framework initialization, or JIT warm-up), then pick from these options:

  1. AppCDS (class data sharing): archive loaded classes so they need not be parsed and verified again. Create one with -XX:ArchiveClassesAtExit=app.jsa (JDK 13+) and run with -XX:SharedArchiveFile=app.jsa. JDK 19+ adds -XX:+AutoCreateSharedArchive.
  2. Do less at boot: trim classpath scanning, reflection, and eager bean creation; use lazy initialization and AOT processing in frameworks like Spring.
  3. Limit the JIT for short-lived tools: -XX:TieredStopAtLevel=1 starts faster but lowers peak speed.
  4. AOT cache (Project Leyden): JDK 24 added ahead-of-time class loading and linking on top of the CDS idea.
  5. GraalVM Native Image: compiles ahead of time to a native executable with start-up in milliseconds and lower memory. The trade-offs are longer builds, closed-world limits on reflection and dynamic proxies, and lower peak throughput without PGO.
  6. CRaC checkpoint/restore: restore a snapshot of an already warmed-up JVM.

Use -Xlog:class+load to see what is loaded. Long-running services should weigh warm-up cost against peak performance, while serverless functions and CLIs usually favor native image or CDS.

Take quiz
Which flag creates a dynamic AppCDS archive when the JVM exits?
-XX:ArchiveClassesAtExit
-XX:+DumpLoadedClasses
-Xshare:off
-XX:SaveClassCache
What is a key trade-off of GraalVM Native Image?
It requires the Serial GC to be disabled
Fast startup and low memory, but closed-world limits and lower peak throughput without PGO
Higher memory use and slower startup than HotSpot
It cannot run on Linux

48. Explain the internal working of card tables and remembered sets?

A generational collector must collect the young generation without scanning the whole old generation. To do that, it needs to know which old objects point into young. Card tables and remembered sets record exactly that.

Card table. The heap is divided into 512-byte cards, with one byte per card in a table. After every reference store (obj.field = ref), a write barrier in the compiled code marks the card containing obj as dirty. At a young GC, only dirty cards are scanned as extra roots, then cleaned. Serial and Parallel GC work this way.

Remembered set (G1). G1 can collect any region on its own, including old ones in mixed collections, so each region keeps a remembered set of the cards in other regions that point into it. A post-write barrier puts dirty cards into thread-local queues, and concurrent refinement threads process them to update the sets.

Collector Mechanism Cost
Serial / Parallel Card table, dirty cards scanned at young GC Light write barrier
G1 Card table plus per-region remembered sets Heavier barrier, extra memory, refinement CPU

In G1 logs, long Update RS or Scan RS phases (-Xlog:gc+phases=debug) point at heavy old-to-young reference churn.

Take quiz
What does a card table help a young GC avoid?
Scanning the entire old generation for references into young
Walking every thread stack twice
Copying survivors into old
Compacting Metaspace
Why does G1 keep a remembered set per region?
To record which threads own each region
To keep a history of System.gc() calls
To store compiled code for each region
So any region can be collected independently by knowing which other regions point into it

49. How do you troubleshoot native memory growth in a JVM?

The usual symptom is process RSS (or a container's memory) growing well past -Xmx while the heap itself stays flat. Work from the JVM's own accounting outwards:

  1. Compare heap against RSS using pmap, /proc/<pid>/status, or container metrics to confirm the growth is outside the heap.
  2. Enable Native Memory Tracking with -XX:NativeMemoryTracking=summary. The JDK docs cite roughly 5-10% overhead, so check before using it in production.
  3. Diff over time: run jcmd <pid> VM.native_memory baseline, then later jcmd <pid> VM.native_memory summary.diff.
  4. See which category grows: Thread, Class, Code, GC, Symbol, or Internal (which includes direct buffers).
  5. If NMT shows nothing growing, the leak is outside what the JVM tracks: JNI or native libraries, memory-mapped files, or glibc malloc arena fragmentation.

Common fixes: cap -XX:MaxDirectMemorySize and fix unreleased buffers (Netty's leak detector helps), cap thread counts since each thread reserves stack memory, set MALLOC_ARENA_MAX=2 or switch to jemalloc for fragmentation, and size the container with headroom above heap.

Take quiz
Which sequence uses NMT to find the growing area?
Take a baseline with jcmd VM.native_memory baseline, then run summary.diff later
Take two heap dumps and diff the hprof files
Run jstat -gc every second
Compare two jstack outputs
Which setting is commonly tried when glibc malloc arenas fragment native memory?
-Xss4m
MALLOC_ARENA_MAX=2
-XX:+UseCompressedOops
-XX:MaxTenuringThreshold=0

50. Explain a systematic workflow for Java performance tuning, from profiling to optimization?

Treat tuning as an experiment loop: define a target, measure, locate the bottleneck, change one thing, and check the result against a baseline.

flowchart TD
  A["Define target, e.g. p99 under 200 ms at 500 rps"] --> B["Reproduce with realistic load and data"]
  B --> C["Record baseline"]
  C --> D["Classify bottleneck: CPU, GC and memory, locks, I/O"]
  D --> E["Profile the suspect area"]
  E --> F["Form hypothesis, change one thing"]
  F --> G["Re-run same workload, compare to baseline"]
  G --> H{Better beyond noise?}
  H -- Yes --> I{Target met?}
  H -- No --> J[Revert] --> E
  I -- No --> D
  I -- Yes --> K["Add regression tests and production monitoring"]
  1. Define the target as a measurable service-level goal.
  2. Reproduce and baseline with a load tool such as Gatling, k6, or JMeter and real-sized data.
  3. Classify the bottleneck using CPU, GC logs, thread states, and database and network timings.
  4. Profile the suspect: CPU with JFR or async-profiler, allocation with the alloc event, waiting with wall-clock or lock profiling, retention with a heap dump.
  5. Change one thing and re-measure with the same workload.
  6. Keep or revert, then repeat until the target is met.

Typical order of attack: queries, algorithms, and I/O first; then allocation and data structures; then concurrency; then GC choice and heap sizing; JIT and OS flags last.

Take quiz
What is the correct order of the tuning loop?
Change JVM flags, deploy, and measure only if users complain
Profile, change five things at once, skip the baseline
Baseline, profile, change one thing, re-measure
Re-measure first, then guess the bottleneck
How do you decide whether to keep a change?
Re-run the same workload and compare against the baseline beyond the noise level
Keep it if the code looks cleaner
Keep it if the heap became larger
Keep it if a microbenchmark of one method improved
«
»

Comments & Discussions