3 Hours

3. JVM Internals & Memory Management

JVM Fundamentals
Sandbox Note: The editor validates your Java syntax and compilation only. It does NOT start a JVM with Spring Boot. When you see Compilation successful (exit code 0), your code is syntactically correct. Copy it to your local IDE and run with ./mvnw spring-boot:run to test.

Understanding how the Java Virtual Machine (JVM) works is crucial for building high-performance Spring Boot applications. The JVM manages memory, executes bytecode, and handles garbage collection. Knowing these internals helps you diagnose memory leaks, optimize performance, and configure your production Spring applications correctly.

How Java Code Runs: Source to Execution

Java uses a two-step compilation process that makes it platform-independent.

Java
// Step 1: You write .java source code
public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello");
    }
}
// Step 2: Compiler (javac) converts to bytecode (.class file)
// Step 3: JVM executes bytecode, converting to machine code via JIT compilation

JIT Compilation

The JVM uses a Just-In-Time (JIT) compiler to identify hot methods (frequently executed code) and compile them directly to native machine code, dramatically improving performance over pure interpretation.

To test locally: Compile with javac HelloWorld.java then run java HelloWorld. The sandbox validates compilation only.

JVM Memory Structure

The JVM divides memory into several regions. Understanding these helps you configure your Spring Boot application's memory settings.

Heap Memory (The Object Storage)

The heap is where all Java objects are stored. Spring Boot creates thousands of objects (beans, controllers, services, repositories) — all live in the heap.

Text
Heap Structure:
┌─────────────────────────────┐
│  Young Generation           │  ← New objects go here
│  ├── Eden Space             │  ← Most objects start here
│  ├── Survivor Space S0      │  ← Objects that survive GC move here
│  └── Survivor Space S1      │
├─────────────────────────────┤
│  Old Generation (Tenured)   │  ← Long-lived objects (Spring Beans)
├─────────────────────────────┤
│  Metaspace (PermGen before) │  ← Class metadata, method info
└─────────────────────────────┘

Stack Memory (Thread Storage)

Each thread gets its own stack. Each method call creates a stack frame containing local variables, parameters, and return addresses.

Java
public void processOrder(Order order) {  // Stack frame 1
    calculateTotal(order);               // Stack frame 2 pushed
    // when calculateTotal returns, frame 2 popped
}  // frame 1 popped
Spring Boot Note: Each HTTP request typically runs in its own thread with its own stack. This is why Spring Boot can handle many concurrent requests.

Garbage Collection (GC)

Java automatically manages memory through garbage collection. The GC identifies objects that are no longer referenced and frees their memory. In Spring Boot applications, the GC runs periodically to clean up temporary objects created during request processing.

Java
// These objects become eligible for GC when no longer referenced
@Service
public class UserService {
    public User findUser(Long id) {
        // 'tempList' becomes eligible for GC after method returns
        List<String> tempList = new ArrayList<>();
        tempList.add("temp data");
        return userRepository.findById(id);
    }
}

GC Generations (Why Young and Old)

  • Young GC (Minor GC): Very fast, cleans Eden and Survivor spaces. Most Spring Boot temporary objects (request-scoped data) die here.
  • Old GC (Major GC): Slower, cleans the Old Generation. Spring Boot beans (which live for the entire application lifecycle) survive here.
GC Tuning for Spring Boot: If your Spring Boot app has frequent Full GC pauses, you may have a memory leak or need to increase heap size.

JVM Configuration for Spring Boot

You can pass JVM arguments when starting your Spring Boot application to optimize memory usage.

Bash
# Basic JVM settings
java -Xms512m -Xmx1024m -jar my-spring-app.jar

# Detailed GC logging
java -Xms512m -Xmx1024m \
  -XX:+PrintGCDetails \
  -XX:+PrintGCTimeStamps \
  -Xloggc:gc.log \
  -jar my-spring-app.jar

# Use G1GC (recommended for Spring Boot)
java -XX:+UseG1GC -Xms512m -Xmx1024m -jar my-spring-app.jar

# For container environments (respect cgroup limits)
java -XX:+UseContainerSupport -XX:MaxRAMPercentage=70.0 -jar my-spring-app.jar
Local Testing: Add these JVM arguments when running your Spring Boot app with java -jar or configure them in your IDE.

Monitoring JVM in Spring Boot

Spring Boot Actuator provides endpoints to monitor JVM metrics.

Text
# application.properties
management.endpoints.web.exposure.include=health,metrics
management.metrics.enable.jvm=true
Bash
# Access JVM metrics
curl http://localhost:8080/actuator/metrics/jvm.memory.used
curl http://localhost:8080/actuator/metrics/jvm.gc.pause

Knowledge Check

Ready to test your understanding of 3. JVM Internals & Memory Management?

Back