Stack and Heap

  • https://www.youtube.com/watch?v=5OJRqkYbK-4
  • https://stackoverflow.com/questions/2565331/fields-of-class-are-they-stored-in-the-stack-or-heap
  • It is an implementation detail as to whether the primitive type or a reference type will really go into stack or heap
  • The reference type just stores the address, but the actual object is always stored in heap (for example by using new keyword)
  • The following is general implementation but not really necessary
    • If you have a variable that needs to be accessed across different methods or some data that needs to be accessible after the method has run, that is going to live on the heap (for example static variables)
    • Class fields (primitive or reference type) go to heap
    • local variables (primitive or reference type) and method arguments are stored in stack frame unless they are part of closure (anonymous class or lambda)
  • Heap has items stored in any order
  • Adding Items to Heap has higher overheads than adding items to stack
class MyClass {
    private int x = 3; // heap
    private Point point = new Point(3, 4); // heap
 
    public void run() {
        int y = 7; // stack
        Point point = new Point(y, y * y); // stack 
 
        int z = 9; // heap because it is enclosed in closure
        new Thread(() -> {
            z++;
        }).start();
    }
}

Stack

  • https://stackoverflow.com/questions/13182374/in-java-is-there-a-way-to-track-if-a-variable-a-method-or-a-class-created-in-h
  • The stack stores stack frames (containing local variables and partial results)
  • Call stack is also known as execution stack
  • The stack frame stores information about methods that have not yet terminated. The information includes the address of a method, parameters, local variables, intermediate computations, and some other data
    • A new stack frame is added when the execution enters a method. And the stack frame is removed from the call stack if the execution of the method is done
    • When your stack contains too many stack frames, it can be overflowed. It leads to the StackOverflowError that will stop the execution

Stack Trace

  • Stack trace represents call stack which consist of list of StackTraceElement
  • StackTraceElement represents stack frame
// Print stack trace
Thread.currentThread().getStackTrace();

Heap

  • Heap is runtime data area
  • Compilation_JVM_JDK
  • Young generation: New objects created
    • Eden space
    • survivor space
  • Old generation:
    • if objects survive young generation multiple GC cycles
    • contains large number of objects
  • Permanent generation (Not in Heap):

Garbage Collection

  • Retrieves and destroys unreferenced java objects from heap area
  • GC is necessary to avoid memory leaks
  • advantages:
    • Reclaim RAM
    • Programmer can focus on logic instead of managing memory
  • disadvantages:
    • It can cause pauses in an application’s execution as it works to clear the memory which slows down the performance
    • They block all the other threads while they are doing their thing
    • It is non-deterministic which makes it difficult to predict when garbage collection occurs
    • It can also increase memory usage if the program creates and discards a lot of short-lived objects.
  • Params:
    • How much long to block JVM
    • How much RAM will be freed up
  • By default JVM allocates 25% of available RAM for heap
    • can be tweaked: -XX:InitialRAMPercentage, -XX:MaxRAMPercentage, -XX:MinRAMPercentage
  • GC can freeze JVM if not handled properly

Garbage Collector Types

  • Serial GC: aka Young generation collector, uses single thread — good for small programs
  • Parallel GC: uses multiple threads
  • G1 GC: Garbage first garbage collector (JDK 9 and above) — good for large heaps
  • Z GC: Z garbage collector (JDK 11 or above)
  • CMS GC: Concurrent Mark sweep garbage collector (deprecated, pre JDK 9)

Garbage Collection Types

  • https://stackoverflow.com/questions/16549066/java-major-and-minor-garbage-collections
  • Young and Older Generations are served by different Garbage Collectors.
  • Minor:
    • aka young generation garbage collection
    • works on young generation: eden + survivor spaces
    • collect and reclaim memory that is used by short-lived objects
  • Major:
    • aka old-generation garbage collection
    • collect and reclaim memory that is used by long-lived objects (objects that survive multiple minor garbage collections and are promoted to the old generation)
  • Full:
    • memories from all generations are collected and reclaimed
    • Full GC runs Minor first followed by Major
    • normally takes longer to complete than a minor or major garbage collection which causes that app to pause temporarily

Garbage collection issues

  • symptoms:
    • long garbage collection pauses
    • frequent collections
    • excessive CPU consumption
  • diagnosis:
    • analyze garbage collection logs
    • choose appropriate GC
    • fine tune GC parameters
    • enable GC logging: -XX:PrintGCDetails or verbose:gc
    • -verbose:gc -XX:+PrintGCDetails -XX:+PrintGCTimeStamp
  • tools:
    • GC easy
    • GC viewer

Memory Leak

  • When objects are no longer needed but still referenced from other reachable objects
  • Creating too many objects unnecessarily
  • Hence it prevents GC to reclaim the memory

Object Interning

  • specific optimization feature of the JVM that involves the reuse of immutable objects
  • Examples:
    • String pool
    • Wrapper classes
      • Boolean (true and false)
      • Character (characters from 0 to 127)
      • Byte, Short, Integer, Long (-128 to 127)
      • No cached instances exist for the Float and Double