JVM basics section 1


#JVM basics section 1

JVM introduction

java Non running on virtual machine platform Java Language program
java source code->Binary bytecode(.class (file) ->JVM-> interpreter->Machine code->CPU
 It only cares about "bytecode" files

Java Not the most powerful language, but JVM Is the most powerful virtual machine
 Virtual machine: virtual computer, which can be divided into system virtual machine and program virtual machine
java Virtual machine is the running environment of binary bytecode
    characteristic:
    1.Write once and run everywhere
    2.Automatic memory management mechanism, garbage collection function
    3.Array subscript out of bounds check
    4.polymorphic
 Composition: class loader, runtime data area, execution engine and local method library

JVM memory area

JVM memory area is mainly divided into thread private area [program counter, virtual machine stack, local method area] and thread sharing area

Domain [JAVA heap, method area], direct memory.

OOM:Out Of Memory out of memory

Memory leak: the memory used by the application is not released, so that the virtual machine can not use the memory again. At this time, this memory is leaked, because the applicant does not use it and can not be allocated by the virtual machine to others.

Memory overflow: when the requested memory exceeds the memory size provided by the JVM, it is called overflow.

thread

thread effect
Virtual machine thread (VM thread)Wait for the JVM to reach the safe point. These operations must be executed in an independent thread, because when the heap modification cannot be carried out, the thread needs the JVM to be at the safe point. These types of operations include: stop the world garbage collection, thread stack dump, thread pause, thread skew lock release
Periodic task threadThis thread is responsible for timer events (i.e. interrupts) to schedule the execution of periodic operations
GC threadThese threads support different garbage collection activities in the JVM.
Compiler threadThese threads dynamically compile bytecode into local platform related machine code at run time.
Signal distribution threadThis thread receives the signal sent to the JVM and calls the appropriate JVM method for processing.

1. Program counter

Program counter( Program Counter register:Register)
  effect:
    Remember the next one jvm Instruction execution address
  characteristic:
    Threads are private, and each thread has its own counter
    There will be no memory overflow

2. Java Virtual Machine Stacks

1.The memory required for each thread to run is called the virtual machine stack
2.Each stack consists of multiple stack frames( Frame)Composition, corresponding to the memory occupied by each method call
3.Each stack can only have one active stack frame, corresponding to the method currently executing   

Problem analysis:

1,Does garbage collection involve stack frames?
    No, the stack will pop up after the method is executed, which will be automatically recycled without garbage collection
2,Is the larger the stack memory allocation, the better?
    No, too much allocation may lead to low efficiency
3,Are local variables in methods thread safe?
    A method local variable is thread safe if it does not escape the scope of the method
    If a local variable references an object and escapes the scope of the method, consider the thread safety of the variable

Stack memory overflow

Too many stack frames cause overflow in the stack
 Stack memory overflow caused by too large stack frame
    java.lang.StackOverflowError Stack memory overflow
    -Xss256k Sets the size of stack memory

Thread run diagnostics

Case 1: CPU Occupied too much
    use top View the process real-time monitoring and locate the process pair CPU The occupation of is too high
    ps H -eo pid,tid,%cpu|grep process id(use ps The command further locates which thread caused it CPU Occupancy too high
    jstack process id

Case 2: the program runs for a long time without results

Deadlock occurred

3. Local method stack

Memory required to call local methods, native Keywords, using C Language and C++Language program

4. Heap

adopt new Keyword. Heap memory is used when creating objects
 characteristic:
    It is shared by threads, so thread safety should be considered in the heap
    There is a garbage collection mechanism

Heap memory overflow

Heap memory overflow: java.lang.OutofMemoryError:java heap space    

Heap memory diagnostics

1.jps tools

View which are in the current system java process

2.jmap tool

View heap memory usage

3.jconsole tools

Graphical interface, multi-functional detection tools,

5. Method area

The heap memory used by the previous permanent generation logically belongs to the heap memory, but in different businesses JVM The method area is implemented differently
    stay java8 After that, the permanent generation is removed and the meta space is used. The occupied memory is local memory and the memory of the operating system

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-rqqgcvhb-1638098894312) (C: \ users \ admin \ appdata \ roaming \ typora \ user images \ image-20211113234505264. PNG)]

Method area memory overflow

Permanent memory overflow before 1.8

Demonstrate permanent generation memory overflow: java.lang.OutofMemoryError:PermGen space
-XX:MaxPermSize=8m

Meta space memory overflow after 1.8

Demonstrate meta space memory overflow:java.lang.OutOfMemoryError:Metaspase
-XX:MaxMetaspaceSize=8m

Runtime Constant Pool

Binary bytecode (class basic information, constant pool, class method definition, including virtual machine instructions)

The constant pool is a table from which the virtual machine instruction finds the class name, method name, parameter type, literal and other information to be executed
 Runtime constant pool*.class When the class in the file is loaded, its constant pool information will be put into the runtime constant pool, and the symbolic address in it will be changed into the real address   
Decompile command:
    javap -v Demo1.class

The information in the constant pool will be loaded into the runtime constant pool. At this time, a, B and ab are symbols in the constant pool and have not been changed into java string objects

ldc #2 will change the a symbol into a string object of "a"

ldc #3 changes the a symbol to a "b" string object

ldc #4 will change the a symbol to an "ab" string object

String s1="a";
String s2="b";
String s3="ab";In string pool

String s4=s1+s2;A new object is created in the heap new stringbuilder().appand("a").appand("b").toString();new String("ab")
    String s5="a"+"b";javac Spliced during compiler"ab",In string pool
    s3==s4 //(false)
because s3 of"ab"Is there StringTable In, and s4 It is a new object stored in the heap in different positions. The comparison returns yes false  
String x="ab";        
String s=new String("a")+new String("b")
Stirng s2=s.intern()Try to put this string object into the string pool. If not, it will not be put. If yes, it will be put into the string pool, and the objects in the string pool will be returned
s2==x	(true)
s==x    (false)

Only when these strings are used will they be loaded from the constant pool into the runtime constant pool

StringTable ["a", "b", "ab"] hashtable structure, cannot be expanded

6. Characteristics of stringtable

The string in the constant pool is only a symbol and becomes an object when it is used for the first time
 The string pool mechanism is used to avoid repeated creation of string objects
 The principle of string variable splicing is StringBuilder(1.8)
The principle of string splicing is compiler optimization
 have access to intern Method to actively put string objects not yet in the string pool into the string pool    
    1.8 Try to put this string object into the string pool. If not, it will not be put. If yes, it will be put into the string pool, and the objects in the string pool will be returned
    1.6 Try to put this string object into the string pool. If there is one, it will not be put. If there is no one, it will copy the object and put it into the string pool, and the object in the string pool will be returned

Interview questions:

public class Demo1 {
    public static void main(String[] args) {
        String s1 = "a";
        String s2 = "b";
        String s3 = "a" + "b";
        String s4 = s1 + s2;
        String s5 = "ab";
        String s6 = s4.intern();

        System.out.println(s3 == s4);//false
        System.out.println(s3 == s5);//true
        System.out.println(s3 == s6);//true

        String x2 = new String("c") + new String("d");
        String x1 = "cd";
        x2.intern();
        //x2.intern();
        //String x1 ="cd";
//        System.out.println(x1 = x2);//true
        System.out.println(x1 = x2);//false
        //If you change the position, what if it's 1.6
        //If there is no in the constant pool, a copy will be copied to the constant pool in the heap
    }
}

7. Location of stringtable

Set in JDK8: - Xmx10m -XXUseGCOverheadLimit

Set in JDK6: - XX:MaxPermSize=10m

It can be proved that StringTable is in heap space (1.8) and in permanent generation (1.6)

8. Performance tuning of stringtable

Adjustment: - XX: StringTableSize = number of barrels

Consider whether to pool string objects (using the intern method)

Direct memory

1. Definitions

Common in NIO operations, used for data buffers

Allocation recovery cost is high, but read-write performance is high

Not managed by JVM memory reclamation

2. Distribution and recovery principle

The Unsafe object is used to complete the allocation and recycling of direct memory, and the freeMemory method needs to be actively called for recycling

Inside the ByteBuffer implementation class, Cleaner (Virtual Reference) is used to monitor the ByteBuffer object. Once the ByteBuffer object is garbage collected, the ReferenceHandler thread will call freeMemory through the clean method of Cleaner to release the direct memory

JVM runtime memory

From the perspective of GC, Java heap can also be divided into Cenozoic (Eden * *, FromSurvivor * * and ToSurvivor * *) and elderly

Generation.

1. Cenozoic

Is used to store new objects. It usually occupies 1 / 3 of the heap space. Because objects are created frequently, the new generation will trigger frequently

MinorGC performs garbage collection. The Cenozoic is divided into Eden District, servirfrom district and servirto district.

Eden area 
Java The birthplace of the new object (if the newly created object takes up a lot of memory, it will be directly allocated to the old age). When Eden It will be triggered when there is not enough memory in the area MinorGC,Carry out a garbage collection in the Cenozoic area
Servivor From
 Last time GC As a survivor of this time GC The person being scanned.
   
ServivorTo    
Reserved once MinorGC Survivors in the process
    MinorGC Process (replication)->empty->(interchangeable)
    MinorGC Replication algorithm is adopted.
1.eden,servicorFrom Copy to ServicorTo,Age+1
     First, put Eden and ServivorFrom Copy live objects in area to ServicorTo Area (if the age of any object and the standard of old age are met, it will be assigned to the old generation area), and the age of these objects will be assigned at the same time+1(If ServicorTo If there is not enough space, put it in the elderly area);
2.empty eden,servicorFrom
    Then, empty Eden and ServicorFrom Objects in;
3: ServicorTo and ServicorFrom exchange
    last, ServicorTo and ServicorFrom Swap, original ServicorTo Be the next GC Timely ServicorFrom Area.

2. Old age

It mainly stores memory objects with long life cycle in the application.
The objects in the old age are relatively stable, so MajorGC Not frequently. In progress MajorGC It's usually done once before MinorGC,The new generation of objects enter the old age, which is triggered when there is not enough space. It is also triggered in advance when a large enough continuous space cannot be found to allocate to the newly created large object MajorGC Make room for garbage collection.
    MajorGC The marker removal algorithm is adopted: firstly, all elderly generations are scanned once to mark the living objects, and then the unmarked objects are recycled. MajorGC It takes a long time because it needs to be scanned and recycled. MajorGC Memory fragmentation will occur. In order to reduce memory loss, we generally need to merge or mark it for direct allocation next time. When the old age is too full to fit, it will be thrown out OOM(OutofMemory)Abnormal.

3. Permanent replacement

Refers to the permanent storage area of memory, mainly for storage Class and Meta(Metadata) information,Class When it is loaded, it is put into a permanent area, which is different from the area where instances are stored,GC Permanent areas will not be cleared during the main program run. Therefore, this also leads to the area of permanent generation will be loaded with the load Class Increase and swell, and finally throw out OOM Abnormal.

4.JAVA8 and metadata

stay Java8 In, the permanent generation has been removed and replaced by an area called "metadata area" (meta space). The essence of meta space is similar to that of permanent generation. The biggest difference between meta space and permanent generation is that meta space is not in the virtual machine, but uses local memory. Therefore, by default, the size of the meta space is limited only by local memory. Class metadata native memory,Put static variables of string pool and class into java In the heap, so that the metadata of how many classes can be loaded is no longer determined by MaxPermSize control,It is controlled by the actual available space of the system.

Keywords: Java jvm Back-end

Added by nivek9991 on Sun, 28 Nov 2021 15:39:22 +0200