Monday, June 16, 2014

Java - GC - garbage collection

Man this is a question always asked at a interview.

everyone reels out the standard - it cant be initiated, the garbage collector gets objects that are not referenced.

Heap - memory allocated to the JVM

-Xmx1024m max size
-Xms512m min size available

the VM tracks live objects. the rest is ok for GC

There are four kinds of GC roots in Java:
  1. Local variables are kept alive by the stack of a thread. This is not a real object virtual reference and thus is not visible. For all intents and purposes, local variables are GC roots.
  2. Active Java threads are always considered live objects and are therefore GC roots. This is especially important for thread local variables.
  3. Static variables are referenced by their classes. This fact makes them de facto GC roots. Classes themselves can be garbage-collected, which would remove all referenced static variables. This is of special importance when we use application servers, OSGi containers or class loaders in general. We will discuss the related problems in the Problem Patterns section.
  4. JNI References are Java objects that the native code has created as part of a JNI call. Objects thus created are treated specially because the JVM does not know if it is being referenced by the native code or not. Such objects represent a very special form of GC root, which we will examine in more detail in the Problem Patterns section below.

jvm runs a mark and  sweep algo

  1. The algorithm traverses all object references, starting with the GC roots, and marks every object found as alive.
  2. All of the heap memory that is not occupied by marked objects is reclaimed. It is simply marked as free, essentially swept free of unused objects.

java algo is impacted by live objects. not dead/free ones - the more live objects the more impact the gc has on the system

GC also does compaction  (packs stuff in heap mem) affects perf

  • Compacting is executed not for every GC cycle, but only once a certain level of fragmentation is reached (e.g., if more than 50% of the free memory is not continuous).
  • One can configure a target fragmentation. Instead of compacting everything, the garbage collector compacts only until a designated percentage of the free memory is available as a continuous block


reduce impact- use concurrent mark and sweep

reduce number of objects if poss


Generation oldies and youngies

new objects are traversed a lot, old objects are moved to the geriatrix divsion and skipped


Copy Garbage collection

two spaces - copy live from one to the other - free the not live area

Oracle hotspot

three areas

Eden, survivor/survivor, tenured (survived multi gc cycles)
things like classes and app code go straight to tenured. not necessary for gc cycle




No comments:

Post a Comment