preface

Just the general, not the details.

Heap structure

About Garbage Collection

  • The Minor GC is for the young generation.
  • Garbage collection generally uses an accessibility analysis algorithm.
  • If the object analyzed by the algorithm for the first time is not cleared, it will be moved to S0 of Servivor region. If the object analyzed by the algorithm for the second time is not cleared, it will be moved to S1. If the object analyzed for the second time is not cleared, it will be moved to S1. It’s going to move from s0 to S1 or from S1 to s0. Each time the generational age of the object head is +1, when the generational age of the object head is equal to 15, it will be moved to the old age, or the object that cannot be placed in the Servivor area will be directly moved to the old age.
  • Objects have not only the data information of the object, but also the header information of the object.

Object head

Garbage collection test

  • A circular reference
public class HeapTest {
    byte[] bytes= new byte[1024*100];//100k

    public static void main(String[] args) throws InterruptedException {// Circular reference
        List<HeapTest> heapTestList = new ArrayList<>();
        while (true){
            heapTestList.add(new HeapTest());
            Thread.sleep(100); }}}Copy the code

The heapTestList object reference is held by HeapTest, and the HeapTest object reference is held by heapTestList. As a result, the reachabability analysis algorithm cannot clear the object and may overflow the memory.

  • Demonstrate a wave of garbage collection with JVisualVM

It can be observed that s0 and S1 are populated alternately, and gc is triggered after Eden’s region is populated.

  • Finally out of memory (OOM)