Skip to main content

4. Java Memory

Java memory management is a crucial aspect of Java programming, affecting how data is stored, accessed, and managed during the execution of a Java program. The Java memory model consists of several components, including the stack, heap, garbage collector, and caches.

1. Stack Memory​

πŸ“ Definition: The stack is a region of memory that stores local variables, method call frames, and references to objects. Each thread has its own stack.

Characteristics:

  • LIFO Structure: Follows a Last In, First Out (LIFO) structure.
  • Automatic Management: Memory allocation and deallocation are managed automatically. Once a method finishes executing, its stack frame is removed, and memory is reclaimed.
  • Size: Typically smaller than heap memory.
  • Primitive Data Types: Stores primitive data types (e.g., int, char) and object references.
public void method() {
int localVariable = 10; // Stored in stack
}

2. Heap Memory​

πŸ“ Definition: The heap is a region of memory used for dynamic memory allocation where objects are created and stored. It is shared among all threads.

Characteristics:

  • Dynamic Allocation: Memory for objects is allocated at runtime.
  • Larger Size: Generally larger than stack memory and can grow as needed.
  • Garbage Collection: Objects in the heap are subject to garbage collection when no longer referenced.
  • Object Data: Stores objects and their instance variables.
public class Example {
public void createObject() {
Example obj = new Example(); // Stored in heap
}
}

3. Garbage Collector​

πŸ“ Definition: The garbage collector (GC) is an automatic memory management system that reclaims memory occupied by objects that are no longer in use.

Characteristics:

  • Automatic Process: Runs in the background and frees memory without explicit deallocation by the programmer.
  • Algorithms:
    • Mark-and-Sweep: Marks live objects and sweeps away dead objects.
    • Generational Collection: Divides objects into generations (young and old) to optimize collection.
  • Performance: Can introduce pauses in execution due to collection cycles.
public class Example {
public void method() {
Example obj = new Example(); // Allocated in heap
obj = null; // Now eligible for garbage collection
}
}

Requesting Garbage Collection​

You can suggest the JVM to run the garbage collector, though this is only a request and not a guarantee that it will run immediately.

System.gc();

Summary of Object Life Cycle​

  • New Object Allocation: Created in the Eden space of the Young Generation.
  • Minor GC: If Eden is full, a Minor GC occurs, and live objects are moved to one of the Survivor Spaces.
  • Aging and Promotion: Objects that survive multiple Minor GCs (and reach the tenuring threshold) are promoted to the Old Generation.
  • Major GC: When the Old Generation fills up, a Major GC occurs to collect long-lived objects no longer in use.

Diagram of object promotion

+--------------+         Minor GC       +-------------------+
| Eden Space | --------------------> | Survivor S0 |
| | +-------------------+
+--------------+ | Minor GC
|---------------------->
| Survivor S1
|---------------------->
| Promoted to Old Gen +----------------+
+--------------------> | Old Generation |
+----------------+

In summary, the movement of an object from the Young Generation to the Old Generation occurs when the object survives a series of Minor GCs and reaches a threshold. This process optimizes memory management by focusing more frequent collections on short-lived objects.

4. Caches​

πŸ“ Definition: Caches are temporary storage areas that hold frequently accessed data to speed up retrieval and improve performance.

Characteristics:

  • Types: Can include CPU caches (L1, L2, L3), disk caches, and application-level caches.
  • Purpose: Reduces the time taken to access data by storing copies of frequently used objects or values.
  • Implementation: Can be implemented using various techniques, such as Least Recently Used (LRU) eviction policies.
// Simple cache implementation example
import java.util.HashMap;

public class Cache {
private HashMap<Integer, String> cacheMap = new HashMap<>();

public void put(int key, String value) {
cacheMap.put(key, value);
}

public String get(int key) {
return cacheMap.get(key); // Retrieves from cache
}
}

Summary of Java Memory Components​

Memory ComponentDefinitionCharacteristics
StackStores local variables and method call frames.LIFO structure, automatic management, smaller size.
HeapUsed for dynamic memory allocation of objects.Larger size, dynamic allocation, subject to garbage collection.
Garbage CollectorAutomatic memory management system.Reclaims memory, runs in the background, can cause pauses.
CachesTemporary storage for frequently accessed data.Improves performance, reduces access time, various implementation strategies.

Very simple program to illustrage Stack vs. Heap​

public class SimpleProgram {
public static void main(String[] args) {
int number = 10; // Primitive stored in Stack
String text = "Hello, World!"; // String object in Heap, reference in Stack
Person person = new Person("Alice", 25); // Person object in Heap, reference in Stack

person.displayInfo(); // Method call on person, uses Stack for local variables
}
}

class Person {
String name; // Field in Heap
int age; // Field in Heap

Person(String name, int age) {
this.name = name; // Fields in Heap
this.age = age; // Fields in Heap
}

void displayInfo() {
System.out.println("Name: " + name + ", Age: " + age); // Local variables in Stack
}
}

Below is a simplified diagram showing how memory is managed for this program:

+---------------------+     +-----------------------------------+
| Stack | | Heap |
+---------------------+ +-----------------------------------+
| main() Frame | | Person Object |
|---------------------| | - name: "Alice" |
| number = 10 | | - age: 25 |
| text (ref) -------->|---->| |
| person (ref) ------>|---->| |
+---------------------+ +-----------------------------------+
↑
|
+---------------------+ | +-----------------------------+
| displayInfo() Frame | +-->+ String Object |
|---------------------| | "Hello, World!" |
| name (from Heap) | +-----------------------------+
| age (from Heap) |
+---------------------+