当前位置:网站首页>[jvm learning] local method stack and heap
[jvm learning] local method stack and heap
2022-06-12 15:14:00 【Aiyouwei】
Native Method Stack
Overview of local method stack
- Java The virtual machine stack is used to manage Java Method call , The local method stack is used to manage calls to local methods
- The local method stack is also thread private
- The memory can be dynamically expanded ( The memory overflow method is the same )
- If the stack capacity allocated by thread request exceeds the maximum allowed capacity of local method stack ,JAVA The virtual machine will throw a StackOverflowError abnormal
- If the native method stack can be dynamically extended , And can't get enough memory when trying to expand , Or when creating a new thread, there is not enough memory to create the corresponding local method stack , that java The virtual machine will throw a OutofMemoryError abnormal
- This non method is to use C The realization of language
- His specific practice is Native Method Stack Registered in native Method , stay Execution Engine Load local method library on execution
- When a thread calls a local method , He entered a world of permissions and no longer restricted by virtual machines . He has the same permissions as the virtual machine
- Local methods can be accessed through local method interfaces The runtime data area inside the virtual machine
- He can even directly use the registers in the local processor
- Allocate any amount of memory directly from the local memory heap
- Not all JVM Both support local methods , because Java The virtual machine specification does not explicitly require the language of the local method stack 、 Specific implementation mode 、 Data structure, etc . If JVM The product is not intended to support native Method , You don't need to implement a local method stack
- stay Hotspot JVM in , Directly combines the local method stack with the virtual machine stack
Local method interface
- Local method : Simple speak , One Native Method It's just one. Java Call not java Code interface , One Native Method It's such a Java Method : This method consists of non Java Language implementation , such as C This feature is not Java Unique to , Many other programming languages have such mechanisms , For example C++ Can be used in extern “C” inform C++ The compiler calls a C Function of
- Defining a native method when , Implementation classes are not provided ( It's like defining a Java interface), Because the realization problem is caused by non - java Language is realized on the outside
- The function of the local interface is to integrate different programming languages into Java used , His original intention was to merge C/C++ Language
- identifier native Can work with all the other java Identifiers are used together , however abstract With the exception of ( because native Represents that there is a method body, but the method body is implemented by other languages , and abstract Yes means there is no method body )
public class IHavaNatives {
public native void Native(int x);
native static public long Native2();
native synchronized private float Native3(Object o);
native void Native4(int[] ary) throws Exception;
}
- Why use it Native Method?
- Java It is very convenient to use , However, some levels of tasks use Java It's not easy to implement , Or when we are concerned about the efficiency of the program , Here's the problem
- And Java Environmental diplomacy is mutual
- Sometimes Java Applications need to be associated with Java The outside environment interacts , This is the main reason for the existence of local methods , Local methods provide us with a very concise interface , And we don't need to know Java Cumbersome details outside the application
- Interact with the operating system
- JVM Supporting Java The language itself and the runtime library , He is Java The platform on which programs live , It has an interpreter ( Interpret bytecode ) And some libraries linked to local code , But anyway , After all, it is not a complete system , He often relies on the support of some underlying systems , These underlying systems are often powerful operating systems , through By using local methods , We can use Java Realization jre Interaction with the underlying operating system , even to the extent that JVM Part of it is to use C Written , And if we're going to use some Java When the language itself does not provide encapsulated features of the operating system , We also need to use local methods
- Sun’s Java
- Sun The interpreter of is through C Realized , This makes it look like something ordinary C Interact with the outside as well , jre Mostly by Java Realized , He also interacts with the outside world through some local methods , for example , class java.lang.Thred Of setPriority() Methods use Java Realized , But it calls the local methods in the class setPriority0. This local method is created by C Realized , And implanted JVM Inside , For a moment java.lang.Thread Class
/* Some private helper methods */ private native void setPriority0(int newPriority); private native void stop0(Object o); private native void suspend0(); private native void resume0(); private native void interrupt0(); private native void setNativeName(String name);
- present situation
- At present, the use of this method is less and less , Except for hardware related applications
Pile up
Overview of heap
- Thread sharing , But the process is private , A process corresponds to a JVM example , One JVM The instance has only one heap memory , So is heap Java The core area of memory management
- Java The heap area is in JVM It is created at startup , The size of the space is determined , yes JVM The largest memory space managed
- The size of the heap is adjustable
- 《Java Virtual machine specification 》 Regulations , The heap can be in a physically discontinuous memory space , But logically, he should be seen as continuous
- All threads share Java Pile up , Here you can also partition the thread private buffer (Thread Local Allocation Buffer,TLAB)
- 《Java Virtual machine specification 》 The description of heap in is : All object instances and arrays should be allocated on the heap at run time
- Arrays and objects may never be stored on the stack , Because the stack frame holds references , This reference points to the location of the object or array in the heap
- At the end of the method , Objects in the heap will not be removed immediately , It's only removed when garbage is collected
- Pile up , yes GC(Garbage Collection, Garbage collector ) Key areas for implementing garbage collection
Subdivision of heap memory
- Most modern garbage collectors are designed based on the theory of generational collection
- Java 7 And before that, heap memory is logically divided into three parts : New Area + Retirement area + The permanent zone
- Youny Generation Space New Area Young/New
- It's divided into Eden Area and Survivor District (Survivor Can be divided into Survivor0 and Survivor1 District , Also known as from Area and to District ,from Area and to Zone uncertainty , The two are often exchanged )
- Tenure generation Space Retirement area Old/Tenure
- Permanent Space The permanent zone Perm
- Youny Generation Space New Area Young/New
- Java 8 And then the heap memory is logically divided into three parts : New Area + Retirement area + Meta space
- Youny Generation Space New Area Young/New
- It's divided into Eden Area and Survivor District (Survivor Can be divided into Survivor0 and Survivor1 District , Also known as from Area and to District ,from Area and to Zone uncertainty , The two are often exchanged )
- Tenure generation Space Retirement area Old/Tenure
- Meta Space Meta space Meta

- Youny Generation Space New Area Young/New
Heap space size settings
- Java The heap is used to store Java Object instances . So the size of the heap is JVM It's set when it starts , You can choose -Xmx and -Xms To set it up
- -Xms Used to represent heap area ( The new generation + Old age ) Start memory for , Equivalent to -XX:InitalHeapSize,-X yes JVM Operation parameters of ,ms yes memory start
- -Xmx Is used to indicate the heap area ( The new generation + Old age ) Maximum memory of , Equivalent to :-XX:MaxHeapSize

- Once the memory size in the heap exceeds -Xmx The maximum memory specified , It will be thrown out. OutOfMemoryError abnormal
- Usually will -Xms and -Xmx Both parameters are configured with the same value , The aim is to be able to Java Garbage collection does not need to separate and calculate the size of the heap after clearing the heap , To improve performance
- By default , Initial memory size : Physical computer memory size /64 Maximum memory size : Physical computer memory size / 4, As shown in the following figure , The reason why it does not display the specific running memory is that it uses the free memory of the machine , And the above Survivor0 Area and Survivor1 Only one area is counted for calculation
public class HeapSpaceInitial {
public static void main(String[] args) {
// return java The total amount of heap memory in the virtual machine
long initialMemory = Runtime.getRuntime().totalMemory() / 1024 /1024 ;
// return java Maximum heap memory the virtual machine is trying to use
long maxMemory = Runtime.getRuntime().maxMemory() / 1024 / 1024 ;
System.out.println("-Xms : " + initialMemory + "M");
System.out.println("-Xmx : " + maxMemory + "M");
System.out.println(" The size of the system memory is :" + initialMemory * 64.0 / 1024 + "G");
System.out.println(" The size of the system memory is :" + maxMemory * 4.0 / 1024 +"G");
/** * -Xms : 243M * -Xmx : 3596M * The size of the system memory is :15.1875G * The size of the system memory is :14.046875G */
}
}
The new generation and the old generation
- Stored in JVM Medium Java Objects can be divided into two categories
- One is transient objects with short life cycle , Such objects are created and die out very quickly
- Another kind of object has a very long life cycle , In some extreme cases, it can also be associated with JVM The life cycle of
- Java If the heap area is further subdivided , It can be divided into the younger generation (YoungGen) And the older generation (OldGen)
- Among them, the young generation can be divided into Eden Space ,Survivor0 Space and Survivor1 Space ( Sometimes it's called from District to District )
- The proportion of the new generation and the old generation in the stack structure is configured
- Default -XX:NewRatio=2, The new generation occupies 1, The old generation occupies 2, The whole stack of the Cenozoic stack 1/3
- You can modify -XX:NewRatio=4, The new generation occupies 1, The old generation occupies 4, The Cenozoic took over the whole pile 1/5

/** * -NewRatio : Set the ratio of the new generation to the old generation The default value is 1:2 * * -XX:SurvivorRatio=8 Set up Eden Space and the other two Survivor The proportion of space The default value is 8 * -XX:-UseAdaptiveSizePolicy : Turn off adaptive memory allocation strategy ( Temporarily unavailable ) * '-Xmn' Set the new generation maximum memory size // Generally not set */
public class EdenSurvivorTest {
public static void main(String[] args) {
System.out.println(" test ");
try{
Thread.sleep(100000000);
}catch (Exception e){
e.printStackTrace();
}
}
}
- stay HotSpot in ,Eden Space and the other two Survivor The proportion of space default is 8:1:1 ( It shows that 6:1:1 The reason is because of the adaptive mechanism -XX:-UseAdaptiveSizePolicy), Manual setting is still required here , Continue the above code , Add to the operating parameters -XX:SurvivorRatio=8

- Developers can use options "-XX:SurvivorRatio" This spatial scale . such as -XX:SurvivorRatio=8
- Almost all Java It's all about Eden Quilt new Coming out
- Most of them Java The objects were destroyed in the new generation
- IBM The company's special research shows that , In the new generation 80% The objects are all life and death
- Options available ’-Xmn’ Set the new generation maximum memory size
- This parameter usually uses the default value
A simple description of object assignment
Allocating memory for new objects is a very rigorous and complex task ,JVM Not only do designers need to think about how memory is allocated 、 Where to distribute, etc , And because the memory allocation algorithm is closely related to the memory recovery algorithm , So we need to think about GC Whether memory fragmentation will occur in the memory space after memory recovery
- new The object of the first place in Eden Park , This area has a size limit
- When the space of Eden fills up , The program needs to create objects ,JVM The garbage collection of will be carried out in Eden Park (Minor GC), Destroy the objects in Eden Park that are no longer referenced by other objects , Then load the new object and put it in the garden of Eden ( The survivor zone is full of no triggers GC, When Eden Park triggers GC The survivors' area will be reclaimed )
- Then move the remaining objects in Eden Park to the survivors 0 District
- If garbage collection is triggered again , At this point, the last survivor is placed in the survivor 0 District , If it is not recycled, it will be put into the survivors 1 District
- If you go through garbage collection again , At this point, the survivors will be replaced 0 District , Then go to the survivors 1 District
- Default experience 15 At the next time, it will be put in the nursing area . You can set the number of times
- Set parameters : -XX:MaxTenuringThreshold= Set it up
- The pension area is relatively leisurely , When the retirement area is out of memory , Trigger again GC:Maior GC, Clean up the memory in the elderly care area
- If the elderly care area has implemented Major GC Later, it was found that the object could not be saved , It will produce OOM abnormal
- java.lang.OutOfMemoryError:Java heap space
- Here's the code , The generated object cannot be recycled , It is stored in the linked list , When the nursing area is full, the above abnormality will be prompted
public class HeapInstanceTest {
byte[] buffer = new byte[new Random().nextInt(1024*200)];
public static void main(String[] args) {
ArrayList<HeapInstanceTest> list = new ArrayList<>();
while(true){
list.add(new HeapInstanceTest());
try{
Thread.sleep(10);
}catch (InterruptedException e){
e.printStackTrace();
}
}
}
}
/** * Exception in thread "main" java.lang.OutOfMemoryError: Java heap space * at com.wjl.java1.HeapInstanceTest.<init>(HeapInstanceTest.java:7) * at com.wjl.java1.HeapInstanceTest.main(HeapInstanceTest.java:12) **/

summary :
For survivors S0,S1 The summary of the district : After copying, there is exchange , Who is empty and who is to
About recycling : Frequent collection of , It's rarely collected in the retirement area , Almost no longer permanent / Meta space collection
source Bilibili Shang Hongkang, teacher song JVM Tutorial notes : Song Hongkang explains in detail java virtual machine
边栏推荐
- 频繁项集产生强关联规则的过程
- 2021-06-27
- Array related content
- Selenium advanced
- Introduction to resttemplate
- Use of boost:: bind() in ROS
- Pta: self test -3 array element cyclic right shift problem (20 points)
- PTA:自测-3 数组元素循环右移问题 (20分)
- Learning is an inhumane thing (becoming an expert's internal mind skill)
- Leetcode daily question - fair candy bar exchange
猜你喜欢

Simple crawler framework: parsing 51job page position information

简单的爬虫框架:解析51job页面岗位信息

Kinect2.0+ORBSLAM2_with_pointcloud_map

SQL cross database injection

三维重建系统 | L3增量运动恢复结构(增量SFM)

NETCORE combined with cap event bus to realize distributed transaction -- Introduction (1)

C main函数

PTA:自测-2 素数对猜想 (20分)

机器人前行、旋转的service编写

Function related matters
随机推荐
Scala download and idea installation of scala plug-ins (nanny level tutorial is super detailed)
Assertion of selenium webdriver
leetcode每日一题-公平的糖果棒交换
C escape character
结构体示例
C data type
ShardingSphere实践(6)——弹性伸缩
Some useful websites
ARM 64指令小记
New features of ES6
2021-06-20
C string
Shardingsphere practice (6) - elastic scaling
odom坐标系的理解
2021-06-27
函数递归示例
Ngork implements intranet penetration -- free
Alibaba, Tencent and pinduoduo set an example, and the new logic of industrial Internet is gradually emerging
同花顺手机炒股开户安全吗
學習是一件逆人性的事情(成為高手的內功心法)