I'm always excited to take on new projects and collaborate with innovative minds.

Mail

say@bplbmki.in

Website

https://www.bplbmki.in/

interviews

JAVA SENIOR DEVELOPER INTERVIEW NOTES (JVM / MEMORY / GC)

================================================

  1. WHAT IS JVM?
    ================================================

JVM (Java Virtual Machine) is a runtime engine responsible for executing Java bytecode.
It provides platform independence by converting compiled Java bytecode into machine
instructions specific to the host operating system.

Key responsibilities:

Flow:
Java Code (.java)

Compiler (javac)

Bytecode (.class)

JVM executes bytecode

Important Point:
Because of JVM, Java follows "Write Once Run Anywhere".

================================================
2. EXPLAIN JVM ARCHITECTURE

Main JVM Components:

  1. Class Loader Subsystem
  2. Runtime Data Areas
  3. Execution Engine
  4. Native Interface
  5. Native Libraries

Architecture Flow:

Class Loader

Bytecode Verification

Runtime Memory Areas

Execution Engine

Native Method Interface

Details:

Class Loader
Loads .class files into memory.

Runtime Data Areas
Stores program data such as objects, methods, and stack frames.

Execution Engine
Executes bytecode using interpreter or JIT compiler.

JNI
Allows Java to interact with native code like C/C++.

================================================
3. DIFFERENCE BETWEEN JVM, JRE, AND JDK

JVM
Java Virtual Machine responsible for executing Java bytecode.

JRE
Java Runtime Environment contains:

JDK
Java Development Kit contains:

Example tools in JDK:
javac
javadoc
jar
jdb

Structure:

JDK
└── JRE
└── JVM

================================================
4. WHAT HAPPENS WHEN YOU RUN "java MyClass"

Step 1
JVM starts and loads the main class.

Step 2
ClassLoader loads required classes.

Step 3
Bytecode verification happens.

Step 4
Memory allocation occurs.

Step 5
main() method execution begins.

Execution Flow:

Program Start

Class Loading

Bytecode Verification

Initialization

Execution

================================================
5. WHAT ARE JVM COMPONENTS?

Main components:

Class Loader
Loads class files.

Runtime Data Areas
Stores memory structures.

Execution Engine
Runs bytecode.

JNI
Allows interaction with native libraries.

Native Libraries
External OS libraries.

================================================
6. WHAT IS CLASS LOADER?

ClassLoader loads Java class files into memory.

Responsibilities:

Load class file
Verify bytecode
Prepare memory
Resolve references
Initialize class

Process:

Loading
Linking
Initialization

================================================
7. TYPES OF CLASSLOADERS

Three types:

Bootstrap ClassLoader
Loads core Java classes.

Platform ClassLoader
Loads platform libraries.

Application ClassLoader
Loads application classes.

Hierarchy:

Bootstrap

Platform

Application

================================================
8. WHAT IS BOOTSTRAP CLASSLOADER?

Bootstrap ClassLoader is the root class loader.

Responsibilities:
Loads core Java libraries.

Examples:
java.lang.*
java.util.*
java.io.*

Location:
JDK/lib directory.

Written in native code (C/C++).

================================================
9. WHAT IS PLATFORM CLASSLOADER?

Platform ClassLoader loads platform specific modules.

Example packages:
java.sql
java.xml
java.management

Introduced after Java 9 module system.

================================================
10. WHAT IS APPLICATION CLASSLOADER?

Application ClassLoader loads application classes from classpath.

Example:

Classes inside project
Libraries in classpath
External jars

This loader loads the main class of application.

================================================
11. WHAT IS PARENT DELEGATION MODEL?

Class loaders follow a hierarchy.

When class is requested:

Step 1
Application ClassLoader checks parent.

Step 2
Parent checks its parent.

Step 3
Bootstrap tries to load first.

If not found → child loads class.

Purpose:

Security
Avoid duplicate classes
Ensure core classes loaded first.

================================================
12. WHAT ARE CLASS LOADING PHASES?

Three phases:

Loading
Linking
Initialization

Loading
ClassLoader loads bytecode.

Linking has 3 parts:

Verification
Preparation
Resolution

Initialization
Static variables initialized.

================================================
13. WHAT IS BYTECODE VERIFICATION?

JVM verifies bytecode before execution.

Checks include:

Type safety
Stack overflow prevention
Illegal memory access
Instruction validity

Purpose:

Prevent malicious code
Ensure program safety.

================================================
14. WHAT IS JIT COMPILER?

JIT (Just In Time) compiler improves performance.

Normal execution:

Bytecode

Interpreter

Machine Code

With JIT:

Frequently executed code compiled into machine code.

Advantages:

Faster execution
Runtime optimization
Improved performance.

================================================
15. WHAT IS HOTSPOT JVM?

HotSpot JVM is the most widely used JVM implementation.

Features:

JIT compilation
Adaptive optimization
Garbage collection
Performance monitoring

HotSpot detects frequently executed code called "Hot Spots".

These parts get optimized aggressively.

================================================
16. WHAT IS TIERED COMPILATION?

Tiered compilation combines:

Interpreter
Client compiler
Server compiler

Levels:

Level 0
Interpreter

Level 1
Simple compilation

Level 4
Highly optimized compilation

Benefit:
Better startup and runtime performance.

================================================
17. WHAT IS METHOD INLINING?

Method inlining replaces method calls with actual method code.

Example:

Before:

calculate()
{
return add(a,b)
}

After optimization:

calculate()
{
return a + b
}

Benefits:

Removes method call overhead
Improves performance.

================================================
18. WHAT IS JVM WARMUP?

JVM warmup refers to the initial period where JVM gathers runtime data.

During warmup:

Interpreter runs code
Hot spots detected
JIT compiles frequently used code

After warmup:
Performance becomes faster.

================================================
19. WHAT IS ADAPTIVE OPTIMIZATION?

JVM monitors program behavior at runtime.

Based on execution patterns JVM:

Optimizes frequently executed code
Applies method inlining
Applies loop unrolling

This dynamic optimization is called adaptive optimization.

================================================
20. WHAT IS CLASS METADATA?

Class metadata contains information about class structure.

Stored in Metaspace.

Includes:

Class name
Methods
Fields
Annotations
Constant pool

Before Java 8 this was stored in PermGen.
After Java 8 it moved to Metaspace.

================================================
END SECTION

 

================================================
SECTION 2: JVM MEMORY MANAGEMENT

  1. WHAT ARE JVM MEMORY AREAS?

JVM divides memory into several runtime data areas.

Main JVM memory areas:

  1. Heap
  2. Stack
  3. Metaspace
  4. Program Counter (PC Register)
  5. Native Method Stack

Explanation:

Heap
Stores objects and class instances.

Stack
Stores method calls and local variables.

Metaspace
Stores class metadata.

PC Register
Stores current instruction being executed.

Native Method Stack
Used for native code execution.

Memory Layout Example:

JVM Memory
├── Heap
├── Stack
├── Metaspace
├── PC Register
└── Native Stack

================================================
22. WHAT IS HEAP MEMORY?

Heap memory is the runtime data area where objects are allocated.

Whenever you create an object using "new", it is stored in heap memory.

Example:

User u = new User();

Here:

Reference "u" → stored in Stack
Object "User" → stored in Heap

Heap is shared among all threads.

Heap is divided into:

Young Generation
Old Generation

Young Generation contains:

Eden Space
Survivor Space S0
Survivor Space S1

================================================
23. WHAT IS STACK MEMORY?

Stack memory stores:

Method calls
Local variables
References to objects

Each thread has its own stack.

Example:

public void method(){
int a = 10;
}

Here:
Variable "a" is stored in stack.

Stack follows LIFO (Last In First Out).

Function call example:

main()

methodA()

methodB()

Each method creates a stack frame.

================================================
24. WHAT IS METASPACE?

Metaspace stores class metadata.

Metadata includes:

Class structure
Methods
Fields
Constant pool
Annotations

Before Java 8:

PermGen was used.

After Java 8:

PermGen was removed and replaced with Metaspace.

Major advantage:

Metaspace uses native memory and grows dynamically.

================================================
25. DIFFERENCE BETWEEN PERMGEN AND METASPACE

PermGen (Before Java 8)

Stored in JVM heap.
Fixed size.
Could cause OutOfMemoryError frequently.

Metaspace (Java 8+)

Stored in native memory.
Automatically expands.
Better memory management.

Comparison:

PermGen

Metaspace

================================================
26. WHAT IS PROGRAM COUNTER REGISTER?

PC Register stores the address of the current instruction being executed.

Each thread has its own PC register.

Example:

Instruction sequence:

Line 1
Line 2
Line 3

PC register keeps track of which instruction is being executed.

Purpose:

Supports thread execution.

================================================
27. WHAT IS NATIVE METHOD STACK?

Native Method Stack is used when Java calls native code.

Example:

Java calling C or C++ library.

Example method:

System.loadLibrary("nativeLib");

Native code runs using the native stack.

================================================
28. WHAT CAUSES STACKOVERFLOWERROR?

StackOverflowError occurs when stack memory exceeds its limit.

Common reasons:

Infinite recursion
Deep method calls

Example:

public void recursive(){
recursive();
}

This causes infinite recursion and stack overflow.

Stack memory size controlled by:

-Xss

Example:

-Xss512k

================================================
29. WHAT CAUSES OUTOFMEMORYERROR?

OutOfMemoryError occurs when JVM cannot allocate memory.

Common causes:

Heap full
Metaspace full
Too many threads
Memory leak

Example:

List list = new ArrayList();
while(true){
list.add(new Object());
}

This continuously creates objects causing heap overflow.

================================================
30. DIFFERENCE BETWEEN HEAP AND STACK

Heap

Stores objects
Shared among threads
Managed by Garbage Collector

Stack

Stores method calls
Thread specific
Automatically cleaned after method completion

Comparison:

Heap

Stack

================================================
31. WHAT IS OBJECT ALLOCATION IN JVM?

Object allocation process:

Step 1
Memory requested from heap.

Step 2
Object created in Eden space.

Step 3
Reference stored in stack.

Example:

User user = new User();

Memory flow:

Stack → reference
Heap → object

Most objects are first created in Eden space.

================================================
32. WHAT IS THREAD LOCAL ALLOCATION BUFFER (TLAB)?

TLAB is a small private memory area inside Eden space.

Each thread gets its own TLAB.

Purpose:

Reduce thread contention.

Without TLAB:

Multiple threads compete for heap allocation.

With TLAB:

Each thread allocates objects locally.

This improves performance significantly.

================================================
33. WHAT IS ESCAPE ANALYSIS?

Escape analysis determines whether an object escapes a method.

Example:

public void test(){
User u = new User();
}

If object is used only inside method → JVM may allocate it in stack.

Benefits:

Reduce heap allocation
Improve performance
Reduce GC pressure

================================================
34. WHAT IS COMPRESSED OOPS?

OOPS = Ordinary Object Pointers.

Compressed OOPS reduces memory usage.

Normally:

Object reference = 8 bytes

With compressed OOPS:

Reference = 4 bytes

Benefits:

Reduced memory consumption
Better cache usage

Enabled automatically when heap < 32GB.

================================================
35. WHAT IS OFF HEAP MEMORY?

Off heap memory is memory allocated outside JVM heap.

Used for:

High performance applications
Large data processing

Example technologies:

ByteBuffer
Netty
Apache Kafka

Benefits:

Reduce GC overhead.

================================================
36. WHAT IS DIRECT MEMORY?

Direct memory is a type of off heap memory used by NIO.

Example:

ByteBuffer buffer = ByteBuffer.allocateDirect(1024);

Advantages:

Faster IO operations.

Used in:

Network applications
High throughput systems.

================================================
37. WHAT JVM FLAGS CONTROL MEMORY?

Important JVM flags:

-Xms
Initial heap size

-Xmx
Maximum heap size

-XX:MaxMetaspaceSize
Maximum metaspace

-Xss
Stack size per thread

Example:

java -Xms2g -Xmx4g MyApp

================================================
38. WHAT IS -XMS?

-Xms defines the initial heap size.

Example:

-Xms2g

This allocates 2GB heap when JVM starts.

Setting equal Xms and Xmx reduces heap resizing overhead.

================================================
39. WHAT IS -XMX?

-Xmx defines the maximum heap size.

Example:

-Xmx4g

Heap cannot grow beyond this limit.

================================================
40. WHAT HAPPENS WHEN HEAP IS FULL?

When heap becomes full:

Step 1
Garbage collection triggered.

Step 2
Unused objects removed.

Step 3
If memory still insufficient:

OutOfMemoryError occurs.

Example error:

java.lang.OutOfMemoryError: Java heap space

================================================
END SECTION

 

================================================
SECTION 3: GARBAGE COLLECTION DEEP DIVE

  1. WHAT IS MEMORY FRAGMENTATION?
    Memory fragmentation occurs when free memory is broken into small non-contiguous blocks, making it hard to allocate large objects even if total free memory is sufficient.

Types:

  1. WHAT IS EDEN SPACE?
    Eden space is part of the Young Generation in the heap.

Example:

User user = new User(); // allocated in Eden
  1. WHAT ARE SURVIVOR SPACES?
    Young Generation has two survivor spaces (S0 and S1).

Purpose:

  1. WHAT IS OLD GENERATION?
    Old Generation (Tenured) stores long-lived objects.
  1. WHAT IS OBJECT PROMOTION?
    Object promotion is moving objects from Young Generation to Old Generation.
  1. WHAT IS MINOR GC?
    Minor GC occurs in the Young Generation.
  1. WHAT IS MAJOR GC / FULL GC?
    Major/Full GC scans the Old Generation (and optionally Young Generation).
  1. WHAT IS GC ROOTS?
    GC Roots are references used as starting points for garbage collection.

Examples of GC roots:

  1. WHAT IS MARK AND SWEEP ALGORITHM?
    Classic GC algorithm:
  2. Mark: Traverse object graph from GC roots, mark reachable objects.
  3. Sweep: Collect unmarked objects and free memory.

Characteristics:

  1. WHAT IS MARK-COMPACT ALGORITHM?
    Improvement over Mark-Sweep:
  2. Mark reachable objects
  3. Compact live objects to reduce fragmentation

Benefits:

  1. WHAT IS COPYING GC?
    Copying GC divides memory into two halves:

Used in Young Generation because most objects die quickly.

Advantages:

  1. WHAT IS STOP-THE-WORLD PAUSE?
    Stop-the-World is when JVM halts application threads to perform GC.

During this pause:

  1. WHAT IS GC OVERHEAD LIMIT EXCEEDED?
    Occurs when GC spends too much time trying to free memory but cannot.
  1. WHAT TRIGGERS GC?
    GC is triggered when:
  1. WHAT IS GENERATIONAL GC?
    Divides heap into generations:

Benefits:

  1. WHAT IS PROMOTION THRESHOLD?
    Promotion threshold is the number of GC cycles an object must survive before moving from Young to Old Generation.

Example:

  1. WHAT IS GC PAUSE TIME?
    GC pause time = duration application threads are stopped for GC.
  1. WHAT IS GC THROUGHPUT?
    GC throughput = percentage of total time not spent in GC.

Formula:

Throughput = (Total time - GC time) / Total time * 100%

Higher throughput → better application performance

  1. WHAT IS SERIAL GC?

Flags:

-XX:+UseSerialGC
  1. WHAT IS PARALLEL GC?

Flags:

-XX:+UseParallelGC
  1. WHAT IS CMS GC?
    Concurrent Mark Sweep (CMS):
  1. WHAT IS G1 GC?
    Garbage First GC (default in Java 11+)

Flags:

-XX:+UseG1GC
  1. WHAT IS ZGC?

Flags:

-XX:+UseZGC
  1. WHAT IS SHENANDOAH GC?

Flags:

-XX:+UseShenandoahGC
  1. WHEN TO USE G1 GC VS ZGC?
  1. WHAT IS CONCURRENT GC?
  1. WHAT IS INCREMENTAL GC?
  1. WHAT IS GC LOG ANALYSIS?

Example JVM flag:

-Xlog:gc*:file=gc.log:time,uptime,level,tags
  1. HOW TO ANALYZE HEAP DUMP?
    Steps:
  2. Generate heap dump:
jmap -dump:live,format=b,file=heap.hprof <pid>
  1. Open in Eclipse MAT
  2. Look for dominator tree, largest objects
  3. Identify potential memory leaks
  4. WHAT IS OBJECT LIFECYCLE IN JVM?
  5. Allocation (usually in Eden)
  6. Minor GC → surviving objects moved to survivor space
  7. Promotion to Old Generation after multiple cycles
  8. Major/Full GC → objects not reachable are removed
  9. Memory reclaimed and reusable

================================================
END SECTION

 

================================================
SECTION 4: ADVANCED GC AND PRODUCTION DEBUGGING

  1. HOW DOES G1 GC WORK INTERNALLY?
  1. WHAT ARE G1 GC PAUSE PREDICTIONS?
  1. WHAT IS G1 OLD GENERATION COLLECTION?
  1. WHAT IS G1 HUMONGOUS OBJECT?
  1. HOW DOES ZGC REDUCE PAUSE TIMES?
  1. HOW DOES SHENANDOAH GC WORK?
  1. DIFFERENCE BETWEEN G1, ZGC, SHENANDOAH
    | Feature | G1 | ZGC | Shenandoah |
    |---------|----|-----|------------|
    | Pause Time | Predictable | <10ms | Low |
    | Heap Size | Moderate | Very large | Large |
    | Compaction | Concurrent + STW | Concurrent | Concurrent |
    | Default Java Version | 11+ | 11+ | 12+ |
  2. WHAT IS CMS GC INTERNALS?
  1. HOW TO CHOOSE GC FOR MICROSERVICES?
  1. WHAT IS GC LOGGING IN JAVA 8/11/17?
-XX:+PrintGCDetails -XX:+PrintGCDateStamps -Xloggc:gc.log
-Xlog:gc*:file=gc.log:time,uptime,level,tags
  1. HOW TO ANALYZE GC LOGS?
  1. WHAT IS THREAD DUMP?
  1. HOW TO ANALYZE THREAD DUMP?
  1. WHAT IS DEADLOCK?
Thread A locks X, waits Y
Thread B locks Y, waits X
  1. WHAT IS LIVELOCK?
  1. WHAT IS THREAD STARVATION?
  1. WHAT IS BLOCKING QUEUE IN JAVA?
  1. HOW TO DEBUG HIGH CPU USAGE?
  1. HOW TO DETECT MEMORY LEAKS?
  1. WHAT TOOLS ARE USED FOR MEMORY ANALYSIS?
  1. HOW TO GENERATE HEAP DUMP IN PRODUCTION?
-XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/tmp/heap.hprof
  1. WHAT IS DOMINATOR TREE?
  1. HOW TO DEBUG OUTOFMEMORYERROR?
  1. WHAT IS GC PAUSE INVESTIGATION?
  1. WHAT IS SLOW THREAD DEBUGGING?
  1. WHAT IS PROFILING IN JAVA?
  1. WHAT IS APPLICATION MONITORING?
  1. WHAT IS CPU SPIKE ANALYSIS?
  1. WHAT IS MEMORY LEAK IN JAVA?
  1. HOW TO PREVENT MEMORY LEAKS?
  1. WHAT IS PRODUCTION DEBUGGING FLOW?
  2. Collect thread dumps
  3. Collect heap dumps
  4. Analyze GC logs
  5. Identify bottlenecks
  6. Apply fixes in code or tuning
  7. WHAT IS GC TUNING?
  1. WHAT IS STOP-THE-WORLD VS CONCURRENT GC?
  1. HOW TO HANDLE HUNG THREADS?
  1. HOW TO ANALYZE THREAD CONTENTION?
  1. HOW TO DEBUG APPLICATION HANGS?
  1. WHAT IS HEAP DUMP ANALYSIS BEST PRACTICE?
  1. HOW TO IDENTIFY LEAKING STATIC REFERENCES?
  1. HOW TO DETECT LARGE OBJECTS IN HEAP?
  1. HOW TO OPTIMIZE THREAD POOLS?
  1. WHAT IS JVM MONITORING?
  1. HOW TO DEBUG MULTITHREADING ISSUES?
  1. WHAT IS OFF-HEAP MEMORY TROUBLESHOOTING?
  1. WHAT IS LARGE HEAP TUNING STRATEGY?
  1. HOW TO DEBUG NATIVE MEMORY LEAKS?
  1. HOW TO DEBUG GC FREQUENCY ISSUES?
  1. HOW TO IDENTIFY LONG-LIVED OBJECTS?
  1. HOW TO ANALYZE APPLICATION LATENCY?
  1. HOW TO HANDLE OUTOFHEAPERROR IN METASPACE?
  1. BEST PRACTICES FOR JVM PERFORMANCE TUNING

================================================
END OF FILE