Understanding JVM Memory Architecture

Optimizing Code in Java

Pavlos Kosmetatos

Lead Engineer @Wealthyhood

What is the JVM?

  • Platform-independent execution environment
  • Converts bytecode (.class) to machine code
  • Memory management and garbage collection
  • Just-In-Time compilation
Optimizing Code in Java

JVM memory architecture overview

The JVM memory architecture

Optimizing Code in Java

Stack memory

  • Memory area for method execution and local variables
  • LIFO (Last-In-First-Out) structure
  • Stores:
    • Local variables
    • Primitive data types
    • Method call information
  • StackOverflowError if size is exceeded
Optimizing Code in Java

Heap memory

  • Stores all objects and arrays
  • new creates an object and allocates it in the heap
  • Managed by garbage collector
  • Dynamic size
  • Divided into generations
Optimizing Code in Java

Memory in action

public void processData() {
    int count = 0;                  // Stack

String name = "Java"; // Heap
List<String> items = // Reference on Stack new ArrayList<>(); // Object on Heap
items.add(new String("Item")); // Object on Heap }
Optimizing Code in Java

Memory-efficient coding patterns

// Inefficient
List<String> list1 = new ArrayList<>();
for (int i = 0; i < 1000; i++) {
    String s = new String("value"); // 1000 objects
    list1.add(s);
}

// Better
List<String> list2 = new ArrayList<>();
String s = "value";  // Single object
for (int i = 0; i < 1000; i++) {
    list2.add(s);
}
Optimizing Code in Java

Summary

  • JVM manages memory through (mainly) stack & heap areas
  • Stack memory -> fast, stores primitives and references
  • Heap memory -> Stores objects
Optimizing Code in Java

Let's practice!

Optimizing Code in Java

Preparing Video For Download...