Sobes.tech
Middle

Kuidas on Java mälu üles ehitatud?

sobes.tech AI

Vastus AI-lt

Memory in Java is managed automatically by the garbage collector and is divided into several regions:

  1. Heap:

    • Stores class objects and arrays.
    • One for all application threads.
    • Garbage collector works with this region.
    • Divided into generations (Young, Old, Permanent).
  2. Stack:

    • Each thread has its own stack.
    • Stores local variables of primitive types and references to objects in the heap.
    • Data is added and removed according to the LIFO (Last-In, First-Out) principle.
    • Automatically freed at the end of the method.
  3. Method Area / PermGen (before Java 8) / Metaspace (from Java 8):

    • Stores information about loaded classes:
      • Class metadata.
      • Bytecode of methods.
      • Static variables.
      • Constant pool.
    • PermGen size was fixed, Metaspace uses native memory and can expand dynamically.
  4. Native Method Stacks:

    • Used for calls to native methods (e.g., C/C++).
    • Freed at the end of the native method.
// Example of memory usage
public class MemoryExample {

    private String instanceVariable; // Stored in Heap

    public void myMethod(int parameter) { // parameter stored in Stack

        int localVar = 10; // localVar stored in Stack

        String localString = "hello"; // "hello" in String Pool (part of Heap/Method Area), reference localString in Stack

        Object obj = new Object(); // Object in Heap, reference obj in Stack

        Integer wrapper = new Integer(5); // Integer in Heap, reference wrapper in Stack
    }

    public static void main(String[] args) {
        MemoryExample example = new MemoryExample();
        example.myMethod(20);
    }
}

Memory regions and their contents:

Region Location What it stores Management
Heap Shared among JVM Objects, arrays Garbage collector
Stack Specific to each thread Local primitives, references to objects Automatic (at method end)
Method Area Shared among JVM Class metadata, static variables, bytecode, constants Garbage collector (for classes and statics)
Native Stacks Specific to each thread (during call) Variables and data of native methods Automatic (at native method end)