Hello everyone, I am xiao CAI, a desire to do CAI Not CAI xiao CAI in the Internet industry. Soft but just, soft praise, white piao just! Ghost ~ remember to give me a three – even oh!

This article mainly introduces the JVM and GC analysis, if necessary, can refer to the Sunday for help, do not forget to praise

Creation is not easy, white piao no righteousness!

First, JVM memory system

The method area and heap are shared by multiple threads in the JVM. Static constants of a class, for example, are stored in the method area and shared between class objects.

The virtual machine stack, local method stack, and program counter are owned independently by each thread and are not shared with other threads.

So when Java creates an instance of a class object through new, it creates a reference to the object in the virtual stack and an instance of the class object on the heap, and points the object reference to the instance of the object. Object references are stored in the corresponding stack frame for each method.

  • Virtual machine stack:For each method executed in the virtual machine stack, a stack frame is created to store information about local variables, operand stacks, dynamic links, method exits, and so on.
  • Local method stack:Similar to the role played by the virtual machine stack, the virtual machine stack serves the Java method, while the local method stack serves the Native method used by the virtual machine. When executing each local method, a stack frame will be created to store information such as local variable table, operand stack, dynamic link, method exit and so on.
  • Methods area:It is used to store files that have been loaded by the virtual machineClass information, constants, static variablesThe method area was called persistent generation in JDK1.7 and before, and has been removed from persistent generation since JDK1.8.
  • Pile:The heap is the storage area for Java objects, allocated for any new fieldsJava object instances and arrays, are allocated on the heap, and the Java heap is available- Xms-XmxFor memory control, from JDK1.7 onwards,Run-time constant poolMoved from the method area to the heap.
  • Program counter:Indicates the next bytecode instruction to be executed by the Java virtual machine.

JVMS after JAVA8

From the figure, we can see that the JVM of JAVA8 has replaced the permanent generation with a meta-space

GC scope

4. Common garbage collection algorithms

Reference counting method:

JVM implementations generally do not take this approach



disadvantages:

  • The reference counter must be maintained every time an object is assigned a value, and the counter itself has some consumption;
  • Harder to handle circular references;

Replication algorithm:

From a GC perspective, the Java heap can be subdivided into the new generation (Eden zone, From Survivor zone, and To Survivor zone) and the old generation. Features: The replication algorithm does not generate memory fragmentation, but consumes space. Used of the Cenozoic era.



MinorGC process (copy -> empty -> swap):

  1. Copy: (copy Eden and SurvivorFrom to SurvivorTo, age + 1) First, when Eden is full, the first GC will be triggered, and the surviving objects will be copied to SurvivorFrom. When Eden and SurvivorFrom trigger GC again, the Eden and From will be scanned. Garbage collection is performed on these two regions, and objects that survive after this collection are copied directly To the To region (if there are objects whose age has reached the old age standard, then copied To the old age area), and the age of these objects is increased by 1.
  2. Clear :(clear Eden and SurvivorFrom) clear objects in Eden and SurvivorFrom, that is, after replication there is exchange, who is empty is to.
  3. Swap :(SurvivorTo and SurvivorFrom swap) finally, SurvivorTo and SurvivorFrom swap, and the original SurvivorTo becomes the next GC’s SurvivorFrom zone.

Mark clearance

The algorithm is divided into two stages, marking and cleaning, marking the objects to be collected first, and then collecting them uniformly. Features: Won’t take up extra space, but will scan twice, time-consuming, easy to produce debris, used for the old age

Label compression

Advantages: No memory fragmentation can be used to take advantage of Bump disadvantages: The cost of moving objects is used for the old age principle:

Mark: Same as mark clearing


Compress: Scan again and slide the live object over a section


Five, determine whether the object is recyclable

Reference counting method

In Java, references and objects are associated. If you want to manipulate objects, you must do so by reference. Therefore, an obvious way to determine whether an object is recyclable is by reference counting. Simply add a reference counter to the object. Each time a reference is made to it, the value of the counter increases by one, and each time a reference fails, the value of the counter decreases by one. An object that has a counter value of 0 at any point in time cannot be used again, so it is a recyclable object. Disadvantages:

It is difficult to solve the problem of objects referring to each other circularly

Enumerating root nodes for reachability analysis (root search path)

A collection of GC roots or tracing GC roots is a set of references that must be active. The basic idea is to start with a series of objects called GC Root and start searching down from this object called GC Roots.

If GC Roots are not connected by any reference chain, this object is not available. That is, given a reference to a set as the root, by reference relations

Which ones can be GCRoots objects

  • The virtual machine stack(Local variable area in stack frame, also called local variable table)
  • The object referenced by the class static property in the method area
  • The object referenced by the constant in the method area
  • The object referenced by N (Native method) in the Native method stack

JVM parameter types

1) Standard configuration parameters

  • java -version
  • java -help


2) X parameter

  • java -Xint -version: Explain execution
  • java -Xcomp -version: Compile native code the first time you use it
  • java -Xmixed: Mixed mode


3) XX parameter

  • Boolean type

-xx: + or – an attribute value (+ : enable, – : disable) Example: -xx: +PrintGCDetails: enable printing GC collection details -xx: -printgcdetails: disable printing GC collection details -xx: +UseSerialGC: enable serial garbage collector -xx: -usesERIalgc: disable serial garbage collector

  • KV setting type

-xx: attribute key = attribute value Example: -xx: MetaspaceSize = 128m: Sets the MetaspaceSize size to 128m. -xx :MaxTenuringThreshold = 15: controls the maximum number of GC promotion times for the new generation to the old generation

  • Jinfo – View the configuration of the currently running program

Jinfo-flag Indicates the process number of the configuration item. Example:

  1. To view the initial heap size:

  2. View other parameters

  3. Check which garbage collector is used

Two classical parameters

  • -xms is equivalent to -xx: InitialHeapSize

  • -xmx is equivalent to -xx: MaxHeapSize

Check the JVM defaults

  • -xx :+PrintFlagsInitial: Displays the default initial value

    • java -XX: +PrintFlagsInitial -version

    • java -XX: +PrintFlagsInitial

  • -xx :+PrintFlagsFinal: View modification updates

    • java -XX:+PrintFlagsFinal
    • java -XX:+PrintFlagsFinal -version
    • java -XX:+PrintCommandedLineFlags


8. Common configuration parameters

Classic case Settings: -Xms128m -Xmx4096m -Xss1024k -XX:Metaspacesize=512m -XX:+PrintCommandLineFlags -XX:PrintGCDetails -XX:UseSerialGC

  • -Xms

Initialize the size of memory, which defaults to 1/64 of physical memory, equivalent to -xx :InitialHeapSize

  • -Xmx

Maximum allocated memory, the default is physical memory 1/4 equivalent to -xx :MaxHeapSize

  • -Xss

Set the size of a single thread. The default is 5112K to 1024K, equivalent to -xx :ThreadStackSize

  • -Xmn

Set the young generation size

  • -XX:MetaspaceSize

Set the metacase size

Similar in nature to persistent generations, metaclases are implementations of method areas in the JVM specification, but the biggest difference between metaclases and persistent generations is that they are not in the virtual machine, but use local memory. Therefore, by default, the size of the meta-space is limited only by local memory.

  • -XX:+PrintGCdetails

Print detailed GC collection log information

  • -XX:SurvivorRatio

Default: -xx :SurvivorRatio=8 –> Eden:S0:S1=8:1:1 -xx :SurvivorRatio=4 –> Eden:S0:S1=4:1:1 SurvivorRatio is the ratio of Eden, S0/S1 is the same

  • -XX:NewRatio

Default: -xx :NewRatio=2 :New generation 1, old generation 2, young generation 1/3 of the heap The Cenozoic generation is 1, the old generation is 4, and the young generation is 1/5 of the whole heap. So the NewRatio is the ratio of the old generation, and the rest is 1 for the Cenozoic generation

  • -XX:MaxTenuringThreshold

Set the maximum garbage age -xx :MaxTenuringThreshold=0: Set the maximum garbage age.

If set to 0, the young generation goes directly to the old generation without passing through the Survivor zone. For older applications, efficiency can be improved. If you set this value to a large value, young generation objects will be copied multiple times in Survivor zones, increasing the lifetime of the object in the young generation and increasing the probability that the young generation will be reclaimed.

Nine, strong weak weak weak


1) Strong references

  • When memory runs out, the JVM starts garbage collection, and for strongly referenced objects,The object will not be recycled even if it appears in OOM
  • Strong references are the most common common object references. As long as there is a strong reference to an object, the name of the object can be returnedaliveThe garbage collector does not touch such objects. The most common in Java is strong references, where an object is assigned to a reference variable that is a strong reference. When an object is referred to by a strongly referenced variable, it is in a reachable state and cannot be collected by the garbage collection mechanism.Even if the object is never used again, the JVM does not reclaim it. So strong references are one of the main causes of Java memory leaks.
  • An ordinary object that has no other reference relationship, exceeds the scope of the reference or explicitly sets the corresponding (strong) reference to NULL is generally considered garbage collected (depending on the garbage collection policy).
public static void main(String[] args) {

        Object o1 = new Object();   // Strong reference by default

        Object o2 = o1;     // Reference assignment

        o1 = null;          // empty for garbage collection

        System.gc();

        System.out.println(o1);     // null

        System.out.println(o2);     // java.lang.Object@1540e19d

    }

Copy the code

2) Soft references

  • Soft reference is a relatively strong reference to weaken some of the reference. Need to use Java. Lang. Ref. SoftReference class to implement, can let the object save some garbage collection.
  • System memorysufficient-> Will not be recycled
  • System memoryinsufficient– > will be recycled
  • Soft references are usually used in memory-sensitive programs, such as caches,When you have enough memory, you keep it and when you don’t, you recycle it
    public static void main(String[] args) {

        Object o1 = new Object();

        SoftReference softReference = new SoftReference(o1);

        o1 = null;

        System.gc();

        System.out.println(o1);

        System.out.println(softReference.get());

    }

Copy the code

3) Weak references

  • Weak references are neededjava.lang.ref.WeakReferenceClass, which has a shorter lifetime than soft references
  • For weakly referenced objects, the garbage collection mechanism reclaims the object’s memory as soon as it runs, regardless of whether the JVM has enough memory.
    public static void main(String[] args) {

        Object o1 = new Object();

        WeakReference weakReference = new WeakReference(o1);

        o1 = null;

        System.gc();

        System.out.println(o1);                     //null

        System.out.println(weakReference.get());    //null

    }

Copy the code

5) Virtual references

  • Virtual reference requirementjava.lang.ref.PhantomReferenceClass to implement.
  • Like dummyIt does not determine the life cycle of the object.
  • If an object holds a virtual reference, it is as likely to be collected by the garbage collector at any time as if it had none at allIt cannot be used alone or accessed through it. Virtual references must be andReferenceQueue (ReferenceQueue)Use in combination.
  • The main purpose of a virtual reference is to track the status of an object being garbage collected, and it simply provides a way to ensure that an object is garbage collectedfinalizeLater, a mechanism for doing something.PhantomReferencetheget()Method always returns NULL, so the corresponding reference object cannot be accessed. The significance is thatIndicates that an object has entered the finalization stage and can be collected by gc for more flexible collection operations than finalization mechanisms.
public static void main(String[] args) {

        Object o1 = new Object();

        ReferenceQueue<Object> referenceQueue = new ReferenceQueue<>();

        PhantomReference<Object> phantomReference = new PhantomReference<>(o1,referenceQueue);

        System.out.println(o1);                         //java.lang.Object@1540e19d

        System.out.println(phantomReference.get());     //null

        System.out.println(referenceQueue.poll());      //null

    }

Copy the code

Extension: Weak reference applies to scenarios

If there is a problem with a reference that needs to read a large number of local images:

  1. If every picture read is read from the hard disk, performance can be severely affected.
  2. Memory overflow may occur if all the files are loaded to the memory at one time.

Use a HashMap to store the mapping between the path of the image and the soft references associated with the image object. When memory runs out, the JVM automatically reclaims the space occupied by these cached image objects, effectively avoiding OOM problems. Map

imgMap = new HashMap

()
,softreference>
,softreference>

WeakHashMap:

public static void main(String[] args) {

        WeakHashMap<Integer,String> weakHashMap = new WeakHashMap<>();

        Integer key = new Integer(1);

        weakHashMap.put(key,1 "test");

        System.out.println(weakHashMap);    / / {1} = test 1

        key=null;

        System.out.println(weakHashMap);    / / {1} = test 1

        System.gc();

        System.out.println(weakHashMap+"\t"+weakHashMap.size());    / / {} 0

    }

Copy the code
They’re all bad guys

Today you work harder, tomorrow you will be able to say less words!

I am xiao CAI, a man who studies with you. 💋