JVM (review) garbage collection and memory allocation strategy

JVM (review) garbage collection and memory allocation strategy

A garbage collector

About garbage collection point we need to summarize, there are three:

  • What needs to recover memory
  • When recycling
  • How to recycle

1.1 What needs to recover memory

The program counter, the virtual machine stack, native method stacks three regions with the threads born, with the threads off

  • With the stack frame stack entry and exit methods and methodical performer pop and push operations, how much memory each stack frame allocated almost certain at compile time, as the method or thread end, which is also part of the memory as can be recycled

java heap and method area is not the same, more of a class that implements the interface of memory needed may be different, you need only know at runtime which objects will be created, which is part of the memory allocation and recovery are dynamic

Moreover, it kept the pile almost all object instances, so this is part of the garbage collection areas of concern

1.2 When recycling

1.2.1 reference counting algorithm

Algorithm principle: adding a reference to the object counter, whenever a reference to its place, the counter value is incremented by 1 when referring to the failure, the counter value is decremented by 1 at any time, the object counter is 0 is no longer in use

However, the algorithm can not solve the problem of circular references:

public class Test{

    static class A{
        private byte[] bytes = new byte[2 * 1024];
        private Object object;
    }

    static class B{
        private byte[] bytes = new byte[2 * 1024 * 1024];
        private Object object;
    }

    public static void main(String[] args) {
        A a = new A();
        B b = new B();
        //相互引用
        a.object = b;   //引用b,b的引用计数器加一
        b.object = a;   //引用a,a的引用计数器加一

        //引用失效,引用计数置为0
        a = null;
        b = null;

        //垃圾回收
        System.gc();
    }
}

Here Insert Picture Description

It can be seen, and not because jvm two objects refer to each other that they can not recover, it can be seen whether the object can be recovered jvm Analyzing Reference counting is not taken

1.2.2 reachability analysis algorithm

Determining whether the object is alive and relevant references

Cited in java

  • Strong references:

    Strong references are very common, such as:

    Object a = new Object();
    

    Such a reference is a strong reference

    As long as the reference is still strong, the garbage collector will never recover them, even if insufficient memory is still not recovered, but throws OOM

  • Soft references:

    Soft references are used to describe some, but not as well as with the necessary object, soft references to objects associated with it, in memory of sufficient time, will not recover, but when memory is low recovery, if recovery of the soft references or not collect enough memory allocation will throw OOM, the use of weak references to achieve SoftReference

            //软引用实现
            String string= "";
            //构造方法传入引用
            SoftReference<String> softReference = new SoftReference<String>(string);
            //此时string便是一个软引用
            string = softReference.get();
    
  • Weak references:

    Description nonessential objects, regardless of whether sufficient memory, as long as the gc, will recover

            //弱引用实现
            String s = "";
            WeakReference<String> weakReference = new WeakReference<>(s);
            s = weakReference.get();
    
  • False quote:

    Whether there is a phantom reference object has completely will not affect their survival time, not to get a virtual instance of an object by reference, the sole purpose of references associated with a set of virtual objects that can be closed when the object is recovered collectors to a system notification

Talk gc root

In fact, reachability analysis algorithm is based on gc root chain of references achieved by GC Root objects as a starting point from which to start the search node down through the search path is called the chain of references, when an object has no references to GC Root chain and GC Root connected useless this object, the object can be recovered.

Here Insert Picture Description

Which can be used as GC Root:

  • VM stack referenced objects
  • Method static property class object referenced by region
  • Methods district constant reference object
  • Native method stacks referenced objects

Any objects directly referenced constants, static variables, global variables, runtime variable method, in principle, be gc

Even unreachable in reachability analysis algorithm objects, and it is not Feisibuke. , And this time they are temporarily out of "probation" stage, at least the death of a real object to go through the process twice marker

  1. After the reachability analysis if the object found during the chain of references is not connected with the GC Roots, he will be the first mark and conduct a screening, filtering criteria is whether this object it is necessary to perform the finalize () method. When the object is not covered finalize () method, or a finalize () method has been invoked over the virtual machine, the virtual machine these two cases are considered "not necessary to perform."

  2. If the object is determined to be necessary to perform a finalize () method, the object could even be placed in a queue called the F-Queue in, and go later by one automatically created by the virtual machine, low-priority thread Finalizer execute it. Here, the term "execution" refers to the virtual machine starting this method does not promise or wait for the end of his run. finalize () method is the last chance to escape death fate of the object, later GC will be F-Queue object in a second small mark, if the object to be successful in their own rescue finalize () in - just to reconnect with any reference to an object related to resume in the chain. finalize () method will only be called once the system automatically.

The method of recovery zone (the permanent generation of HotSpot)

In the stack, particularly in the new generation, a garbage collection may be generally 70% to 95% recovery of space, and the permanent generation garbage collection efficiency is much lower than this.

Two permanent generational garbage collection main parts: constants and useless waste classes.

Analyzing waste constants: Usually the constant is determined not by reference.

Analyzing useless categories: to the following three conditions are met

  • All instances of the class have been recovered, which is the Java heap any instance of that class does not exist
  • Load class ClassLoader has been recovered
  • Java.lang.Class corresponding to the class object does not referenced anywhere chanting, not reflected by the method of accessing the class anywhere

1.3 How to recycle

1.3.1 mark - sweep algorithm

First mark all objects need to be recovered, after marking is completed, it is marked objects uniform recycling

Here Insert Picture Description

defect:

  • Efficiency

    • Mark and sweep efficiency of the two processes is not high
  • Space issues

    • Will produce a large number of discrete memory fragmentation after marking clear, when you need to allocate a large object, you can not find enough contiguous memory and had to trigger a garbage collection

1.3.2 replication algorithm

Replication algorithm to solve the mark - sweep efficiency of the algorithm

He is the available memory capacity is divided in accordance with size equal to two, each of which only one, when it runs a memory, and will also copy live objects to another one, and then the memory space has been used once clean out

Here Insert Picture Description

The cost of this algorithm is to reduce by half the memory, and the survival rate at higher objects, require multiple copy operation, efficiency is reduced at this time

1.3.3 Mark - Collation Algorithm

Tags to organize the same algorithm and mark the first phase of clear mark, the first mark all the recyclable objects, then, is not a finishing mark of recyclable objects to clean up, but to all surviving objects are moved to the end, and then directly to clean up memory other than the end border.

Here Insert Picture Description

1.3.4 generational collection algorithm

For the few, and the old heap into the new generation's, using the most appropriate algorithm based on the characteristics of the individual's memory is divided according to the objects do not have survival period

  • Cenozoic:
    • Every new generation garbage collection has a large number of dead objects, only a few survived, the use of replication algorithm, only need to pay the cost of reproduction of a small amount of live objects can be completed collect
  • Old year:
    • Old's target higher survival rate, there is no extra space assigned a security, must mark - sweep or mark - Collation Algorithm

1.4 garbage collector

Collection algorithms is the methodology of memory recovery, achieved concrete garbage collector memory is recovered

Get their own mind map:

Here Insert Picture Description

Second, memory allocation

Target memory allocation, general direction, is how to allocate the heap

java heap generational:

img

Objects priority allocation in Eden

In most cases, the object allocation in the new generation Eden District, Eden area when there is not enough memory space is allocated, the virtual machine will launch a Minor GC

Large objects directly into the old year

Large objects (java object requires a lot of contiguous memory space, or an array of long strings) will go directly to the old year

Long-term survival of the object will enter the old year

Each object has an age counter, the object after the first minor gc area Eden still alive, and can be accommodated Survivor, it will move to the Survivor partition, and the age is set to 1, then, in each survivor after undergoing a minor gc can survive, age + 1; when the age reaches a certain level (default 15 years) goes to the old era, but not necessarily say that this age must meet before they can enter the old era, if, survivor space of the same age the sum of all objects larger than half the size of the space survivor, age greater than or equal to the target age can go directly to the old year

Published 254 original articles · won praise 136 · views 30000 +

Guess you like

Origin blog.csdn.net/weixin_41922289/article/details/103303300
Recommended