Java Memory Management

When does the garbage collector free up heap memory?

All is taken care of by JVM

Algorithm used by GC: Mark & Sweep

Mark: JVM mark those objects which are being referenced (Has Connection to Stack Memory).

Sweep: JVM sweep those objects which are no longer be used or referenced.

  • Normal Sweeping: It sweeps unmarked (red colored) objects and keep the gaps as it is. This might result OutOfMemoryError.

    OutOfMemoryError:

  • Sweeping with compacting: It compacts the remaining gaps after sweeping unmarked objects. This is better than normal sweeping.

  • Sweeping with copying: It copies the marked objects instead of removing and compacting objects. It then makes original memory empty.

Different types of Memory:

  1. Heap Memory:

    1. Young generation : Copying objects from young generation to old generation. This is expensive operation.

      a. Eden Space: New objects are created in Eden Space and as soon as it reaches a certain threshold, GC starts and moves objects still alive to the survivor space and cleaining up the Eden Space.

      b. Survivor Space: When GC comes by then it moves all the alive objects to Old generation cleaning up the survivor space.

    2. Old generation

  2. Non-heap memory:

    1. Permanent-generation (Metaspace) or PermGen:

Types of Garbage Collectors:

  1. Serial GC:

    1. It uses mark and copy for Young generation & mark sweep compact for Old generation.

    2. It runs on a single thread.

  2. Parallel GC:

    1. It uses mask and copy for Young generation & mark sweep compact for Old generation.

    2. It runs on multiple threads.

  3. Concurrent Mark Sweep GC:

    1. It uses mark and copy for Young generation & mark sweep compact for Old generation.

    2. It runs on multiple threads.

  4. Garbage-First (G1) GC:

    1. Divides heap into small regions

    2. Keep track of amount of live and dead objects

    3. Aims for shortest pauses possible

    4. Runs on multiple threads

  5. Z GC:

    1. Sims for max 10ms pauses

    2. Reference coloring

    3. Sweep and copy

    4. Load barriers

    5. Runs on multiple threads

JVM Tuning:

JVM Tuning is typically the last step to improve the performance of an application

Before JVM tuning as yourself the following questions:

  1. Is the memory functioning all right?

  2. Is the latency all right?

  3. Is the throughput normal?

Metaspace:

  1. Once it reaches its limits, it expands

  2. Set a miximum size

  3. Set a threshold for GC

  4. Set minimum and maximum free ratio

How to prevent memory leak / OutOfMemoryError in JVM ?

  1. Set the objects to null in certain specific situations

  2. Close resources such as streams, file connection, db connections

  3. Avoid string concats; use string builder instead

  4. Careful with static collections holding objects

  5. Overwrite hashCode and equals (especially when custom objects get added to hash sets)