Garbage Collector/Collection (GC)
  • tracks each and every object available in the JVM heap space and removes unused ones

GC - Steps

In simple words, GC works in two simple steps known as Mark and Sweep:

  • Mark - starts from the root node of your application(main), walks the object graph:
    • marks objects that are reachable as live
    • mark objects that are not reachable as dead
  • Sweep - delete unreachable objects
  • Compacting - compact the memory by moving around the objects and making the allocation contiguous than fragmented

GC - Advantages & Disadvantages

Advantages:

  • No manual memory allocation/deallocation handling because unused memory space is automatically handled by GC
  • No overhead of handling Dangling Pointer
  • Automatic Memory Leak management (GC on its own can’t guarantee the full proof solution to memory leaking, however, it takes care of a good portion of it)

Disadvantages:

  • Since JVM has to keep track of object reference creation/deletion, this activity requires more CPU power than the original application. It may affect the performance of requests which required large memory
  • Programmers have no control over the scheduling of CPU time dedicated to freeing objects that are no longer needed
  • Using some GC implementations might result in application stopping unpredictably
  • Automatized memory management will not be as efficient as the proper manual memory allocation/deallocation

GC - Implementations

Serial GC

  • java -XX:+UseSerialGC -jar main.jar
  • single-threaded gc on both young and old generation

Parallel GC

  • java -XX:+UseParallelGC -jar main.jar
  • multi-thread gc on young generation
  • single-threaded on old generation
  • java -XX:+UseParallelOldGC -jar main.jar
  • multi-threaded gc on both young and old generation
  • java -XX:+UseParNewGC -jar main.jar
  • multi-threaded gc on young generation

CMS GC
DEPRECATED

  • java -XX:+UseConcMarkSweepGC -jar main.jar
  • use CMS gc
  • autoenables UseParNewGC

G1 GC

  • java -XX:+UseG1GC -jar main.jar
  • use G1GC

Z GC

  • java -XX:+UseZGC -XX:+UnlockExperimentalVMOptions -jar main.jar
  • java -XX:+UseZGC -jar main.jar
  • use ZGC

Subpages