当前位置:网站首页>JVM series - stack and heap, method area day1-2

JVM series - stack and heap, method area day1-2

2022-07-04 13:44:00 Concise programming

Stack

Java Virtual Machine Stacks (Java Virtual machine stack )
The memory space required for the thread to run , Multiple threads, multiple stacks

The structure of the stack

The stack contains multiple stack frames [Frame]( Chain call ), Stack frame is the memory needed by each method when it runs
Each method needs to occupy memory when executing ( Parameters 、 local variable 、 The return value needs to allocate memory )
When each method needs to be executed , The stack frame will be pushed into the stack , Until the method is executed , The stack frame will come out
Be careful !: Each thread can only have one active stack frame , Corresponding to the method being executed

First in, then out

 Insert picture description here

Push

 Insert picture description here

Out of the stack

 Insert picture description here

Stack demonstration

package stack;

public class StackTest {
    

    public static void do1(int a) {
    
        do2(a, 2);
    }

    public static int do2(int a, int b) {
    
        return a * b;
    }

    public static void main(String[] args) {
    
        do1(2);
    }
}

Enter the code break point into the debug view

How to be in IDEA View specific debugging information in

 Insert picture description here

Stack structure view

 Insert picture description here
 Insert picture description here
Here we see that the whole stack structure is :main The method is at the bottom , And then there was do1, And finally do2, Next, execute the stack
 Insert picture description here
notice do2 The method disappeared first , Explain the last execution do2 Methods are first pushed out of the stack , If you look at the next variable window , You can see the memory usage of variables

We can also see in the method : There is a number after the number  Insert picture description here
This is the code line of the corresponding program ( Program counter function !!!), According to this address information, the execution order can be locked

The characteristics of the stack

  1. The stack does not require a garbage collection mechanism !
  2. The memory of the stack is not as large as possible ! By default, the default size of the stack is 1024KB(windows The system depends on the size of the virtual space ), The larger the memory of the stack, the less the number of threads , Instead, the operation efficiency becomes lower
  3. If the local variables in the method are not out of the scope of the method, then thread safety , Otherwise, the thread is not safe

Stack overflow problem (StackOverflowError)

Also known as stack memory overflow

The cause of the spill

1. Too many stack frames lead to , When a method makes a recursive call , Failure to set the correct termination condition leads to overflow ), It may also be caused by the cyclic dependency of the program
2. Memory overflow caused by too large stack frame , We can imagine this scenario , When making recursive calls , Our method uses variable length parameters , As a result, there are so many parameter variables that the stack frame exceeds the stack memory , But in fact, it's almost impossible to see

IDEA Customize stack memory size

Select edit configuration
 Insert picture description here
Select Modify options –> add to VM Options
 Insert picture description here
Input -Xss128k It can be changed to 128k The size of
 Insert picture description here

Thread running diagnostics (linux)

stay linux In the environment , We can use ps View Thread occupancy ,top You can view the process occupancy

ps H -eo pid,tid,%cpu | grep  process id

By using jstack Command to diagnose the process , List threads , We will thread id Convert to 16 You can know the problem caused by a specific thread by locking it (nid)

jstack  process id

It is recommended to use jconsole or jvisualvm

Native Method Stack

Native Method Stacks
When the local method interface is called , The local method stack provides memory space for it

Pile up

Heap
We use new The object created by keyword will use heap memory

Characteristics of reactor

  1. Thread sharing , Thread safety needs to be considered
  2. There is a garbage sharing mechanism in the heap

Heap overflow problem (OutOfMemoryError)

When our program constantly generates new variables , But these variables will be generated when they are used all the time , Because the garbage collection mechanism does not take effect at this time ,

IDEA Custom heap size

The same way as stack , As long as it is set to :-Xmx Heap size that will do

Heap memory diagnostics

1. jps

It is used to view what are in the current system Java process

jps

2. jmap

Used to view the occupancy of the heap ( Some time )

jmap -heap  Process number 

3. jconsole

For continuous monitoring , contain GUI, It is a multifunctional monitoring tool !

jconsole

 Insert picture description here
Select the process you want to monitor
 Insert picture description here
 Insert picture description here

4.jvisualvm

 Insert picture description here
Heap dump dump: Monitor the complete heap details
 Insert picture description here

 Insert picture description here
Select search in the check to view class information

Method area (jdk1.8 Move back to local memory )

Logically part of the heap , Do not force position , It's a norm

The memory structure of the method area. The information saved by the method area includes :

  1. Type information : It includes JVM Load type ( class class、 Interface interface、 enumeration enum、 annotation annotation) Full valid name of ( Package name + Class name )、 The full and valid name of its immediate parent 、 Type modifier 、 List of interfaces directly inherited .
  2. Domain ( Member variables ) Information : Information about all member variables of type and the declaration order of member variables .
  3. Methods information : Include the name of the member method of the type 、 Return type 、 parameter list 、 Modifier 、 Bytecode 、 The stack of operands 、 Local variable table 、 Exception table, etc .
  4. Static variables :non-final Static class variables and global constants . The difference is that global constants are assigned values by the compiler , Static class variables are assigned initial values in the preparation stage of loading , In the initialization phase, specify the value .
  5. JIT Code cache : Code cache generated by instant compilation , Compile the hotspot code into machine code related to the local platform , And save it to memory .
  6. Runtime constant pool : Various literal quantities and pair types 、 Symbolic references to fields and methods .

Similarly, there will be memory overflow in the method area , And throw it like a heap OutOfMemoryError It's abnormal ( Proved the logical definition )

 Insert picture description here

because StringTable It will be widely used in the program , If placed in the method area ,StringTable Low recycling efficiency will lead to insufficient memory in the permanent generation , So from 1.7 rise StringTable Move into the pile
 Insert picture description here

Constant pool

A table used to view binary bytecode after compilation
The virtual machine instruction finds the class name to execute according to this constant table 、 Method name 、 Parameter type 、 Literal quantity and other information

Runtime constant pool

The constant pool is *.class In the document , When the class is loaded , Its constant pool information will be put into the runtime constant pool , And change the symbolic address into the real address

StringTable

yes hashtable Structure , It can't be expanded
When our program runs , The information in the constant pool will enter the runtime constant pool , The symbol in the constant pool does not change to Java String object , Until the program executes the corresponding statement, it will enter StringTable in

characteristic

  1. Strings in the constant pool are just symbols , When it is used for the first time, it becomes an object using the mechanism of string pool , To avoid creating string objects repeatedly
  2. The principle of string variable splicing is StringBuilder (jdk1.8)
  3. The principle of string constant splicing is compile time optimization
  4. have access to intern Method , Take the initiative to put string objects that are not in the string pool into the string pool , If there is one, it will not put , If not, put it into the string pool , Will return the objects in the string pool (jdk1.8)

When string variables are spliced

use new StringBuilder.append("str1").append("str2")....toString() Equivalent to direct new String("str")
(str = str1+str2…)
( reason : Results can only be determined during operation )

When string constants are spliced

Directly merge the results , And add StringTable in ( reason : The results are directly determined during compilation )

StringTable The garbage collection of

Set up VM Options : -Xmx8m -XX:+PrintStringTableStatistics -XX:+PrintGCDetails -verbose:gc
-Xmx8m : Set heap to 8mb
-XX:+PrintStringTableStatistics: Set up printing StringTable Statistics
-Xlog:gc* : Set print garbage collection details


// Set up VM Options : -Xmx8m -XX:+PrintStringTableStatistics -Xlog:gc* -verbose:gc
//-Xmx8m :  Set heap to 8mb
//-XX:+PrintStringTableStatistics: Set up printing StringTable Statistics 
//-Xlog:gc* : Set print garbage collection details 
public class StringTableGC {
    
    public static void main(String[] args) {
    
        int i = 0;
        for (int j = 0; j < 100000; j++) {
    
            // Join in StringTable in 
            String.valueOf(j).intern();
            i++;
        }
        System.out.println(i);
    }
}

loop 100 Time
 Insert picture description here
loop 10w Time
You can see here that a lot of garbage collection is triggered
After reading, I found that there are 4 Time
 Insert picture description here

StringTable performance tuning

  1. Mainly adjustment hashTable Number of barrels in ( At least 1009 individual )
-Xms500m -Xmx500m -XX:+PrintStringTableStatistics -XX:StringTableSize=1010
  1. Adopt string pooling operation to greatly reduce repeated strings
String.intern()
原网站

版权声明
本文为[Concise programming]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/185/202207041017548219.html