关于java gc

Garbage Collection

  • Why
    More effectively manage dynamic memory allocation, during program execution, there are many dynamically created objects. When some objects are out of scope and we will never use again. We need have a way to release the Heap space used by those objects.

  • What
    Java GC is the mechanism that will automatically detect and delete the unused objects, so developers do not need to care too much about each object’s life cycle. One of the backend threads when JVM is running. Will monitor the heap.

  • How Java GC works

    • Marking (alive objects | unreferenced objects) => how to mark
    • Deletion (Normal Deletion | Deletion with Compacting) => how to optimize
      So, how to mark? Based on the dependency of objects. Start from GC roots, find all reachable objects, those objects can not be deleted. GC roots include 1) all local variables on the stack 2) Static variables of class 3) Active Java Threads. 4) JNI
      Delete with Compacting will move objects in the heap, that means the java program should be stopped, which is called “stop the world” event. If the server is using Java, the heap size is 100GB, it might take a few seconds to do the GC, the delay of response will be a big problem. So, we need the Generation Mechanism. Young Generation, Old Generation, Permanent Generation. Do GC on young generation first, if still not enough space, then old generation, then permanent generation. And there will be a promotion for object. If an object is still alive after several rounds of GC, it will be moved to next generation.
  • Still possible Memory Leak? Yes!!
    Every time we need to assign a task to a new thread, we keep creating a new thread. All active threads are the GC root and can not be GC, this leads to memory leak. Solution => Thread Pool
    If a strong reference has a global scope, then the object can not be GC anymore. => Soft, Weak reference.


Strong Reference

The most common reference type, such as String a = “abc”, a is a strong reference. An object that has a strong reference will not be GC.

Soft Reference

We can create a soft reference for an object. Assume an object has only soft references. If the JVM still has enough memory, then GC will not collect the object. If memory space is not enough, then GC will collect the objects that only refenced by soft reference.

Weak Reference

A weak reference will not affect the GC. If you just want to have reference a object and do not wish do affect it life cycle. Use weak reference. If an object is only reference by weak references. It will be GC for sure.