Memory, GC, class loading, profiling and tuning
Practise these as flashcards. One or two lines each; the ones you miss come back first.
Start freeHeap memory is used for storing objects and is managed by garbage collection, while stack memory holds method call frames and local variables, and is managed per thread. Stack memory is faster but limited in size, whereas heap is larger and shared across threads.
Metaspace stores class metadata, such as class definitions and related structures. Unlike the old PermGen, metaspace is allocated from native memory and grows as needed, reducing the risk of class metadata exhaustion.
Generational GC divides heap into Young and Old generations, optimizing for short-lived objects by collecting them frequently in the Young generation. This reduces the overhead of scanning the entire heap, improving GC efficiency and application performance.
I would use jcmd <pid> GC.heap_dump <file> or jmap -dump:format=b,file=<file> <pid> to capture a heap dump for analysis.
G1 GC divides the heap into regions and prioritizes collecting regions with the most garbage. It performs concurrent marking and evacuation to minimize pause times. I use G1 GC for applications requiring predictable pause times and moderate throughput, especially in large heap scenarios.
I would enable heap dumps with -XX:+HeapDumpOnOutOfMemoryError, collect the dump, and analyze it using tools like Eclipse MAT to find memory leaks or large objects. I also check JVM logs and use jcmd or jmap for real-time analysis.
A thread dump shows all threads and their stack traces. By analyzing thread dumps with jstack, I can identify threads stuck in loops or locks, which often cause high CPU. Tools like async-profiler help visualize CPU hotspots and pinpoint problematic code.
JIT compilation converts frequently executed bytecode into optimized native code at runtime, improving performance. However, initial execution may be slower until the JVM identifies hotspots and applies optimizations, so proper warm-up is important for accurate profiling.
A common issue is ClassNotFoundException due to missing or misconfigured JARs. I check the classpath setup, verify dependencies, and ensure there are no conflicting versions. Tools like jdeps and examining the class loader hierarchy help resolve these issues.
-Xmx sets the maximum heap size, while -XX:MaxRAMPercentage configures heap as a percentage of available RAM, which is useful in containers. These flags help control memory usage and prevent the JVM from exceeding system or container limits.
This flag instructs the JVM to generate a heap dump automatically when an OutOfMemoryError occurs. It is crucial for post-mortem analysis, allowing engineers to investigate memory leaks or excessive object retention after a failure.
I use JVM flags like -Xlog:gc* or -verbose:gc for logging, and tools like JMX, Prometheus exporters, or Grafana dashboards to track heap usage, GC pauses, and allocation rates in real time.