当前位置:网站首页>Runtime. getRuntime(). GC () and runtime getRuntime(). The difference between runfinalization()
Runtime. getRuntime(). GC () and runtime getRuntime(). The difference between runfinalization()
2022-07-03 09:48:00 【Enter the sky with one hand】
List of articles
Preface
Many friends may not have used or even seen these two methods , But as a java Development , You must have seen System.gc();
With this idea , Let's move on
One 、Runtime.getRuntime().gc()
1. And System.gc() contrast
Let's drive System.gc() Source code , I found that it was actually a call Runtime.getRuntime().gc() , So they are equivalent . It's just that we usually use jdk For us System class
2. Official statement
Runtime.getRuntime().gc() Method , The official comment is like this :
Which translates as :
stay Java Run the garbage collector in the virtual machine .
Call the gc The method shows that Java Virtual machines spend energy recycling unused objects , To make the memory they currently occupy available for Java Virtual machine reuse . When control returns from a method call ,Java The virtual machine has done its best to reclaim space from all unused objects . There is no guarantee that this work will recycle any specific number of unused objects , Reclaim any specific amount of space , Or at any particular time ( If any ) Complete before or forever after the method returns . There is no guarantee that this effort will determine the accessibility changes of any specific number of objects , Or any specific number Reference Objects will be cleared and queued .
call System.gc() In fact, it is equivalent to calling :Runtime.getRuntime().gc()
Two 、Runtime.getRuntime().runFinalization()
1. And System.runFinalization() contrast
Again , Let's drive System.runFinalization() Source code , I found that it was actually a call Runtime.getRuntime().runFinalization() , So they are equivalent .
2. Official statement
Runtime.getRuntime().runFinalization() Method , The official comment is like this :
Which translates as :
Run the termination method of any object waiting for termination . Calling this method indicates Java Virtual machines will work hard finalize Found and discarded but finalize Method of an object that has not been run . When control returns from a method call ,Java The virtual machine has done its best to complete all unfinished terminations .
call System.runFinalization() In fact, it is equivalent to calling : Runtime.getRuntime().runFinalization()
Runtime.getRuntime().runFinalization() Is and object Of finalize() Used in combination with
however , from Java9 Start ,object Of finalize() The method has been labeled @Deprecated Out of date
therefore , It is no longer recommended to use Runtime.getRuntime().runFinalization() Conduct gc 了
Be careful : In the latest java18 in ,finalize() and runFinalization() Has been marked as deprecated ,, It is no longer a simple expiration , It may be deleted in the future
3. Why not recommend finalize()
- The timing of the call is uncertain
although finalize() Method will be called sooner or later , However, the uncontrollability of this call timing may lead to system level exceptions due to the delayed release of resources . Because computer resources are limited , When it is clear to release some resources ( For example, in the example above reader A series of resources under control ), Other methods should be used to release these resources immediately - Affect code portability
Because of every kind of JVM The built-in garbage collection algorithms are all different , So maybe in your JVM in , You worked hard to write the use finalize The case of method works well , But transplant to different JVM In the middle of the day , It is likely to collapse in a mess ! - The high cost
If a class is overloaded finalize Method and implements some logic inside the method , that JVM Before constructing or destroying objects of this class , Will do a lot of extra work . Obviously , If a class is not overloaded finalize Method , Then when destroying, just deal with the memory in the heap , And if it's overloaded finalize Method words , To carry out finalize Method , In case there are some exceptions or errors in the execution process , The cost of consumption is even higher . - Abnormal loss
In case fianlize Exception thrown in method , that finalize Will terminate the operation , And the exception thrown will also be discarded , Eventually, the object instance will be in a zombie state of semi destruction and semi survival , Lead to unexpected consequences !
This clip is referenced from :
https://www.bilibili.com/read/cv4055723
3、 ... and 、 test GC
Maybe we are all professional players of eight part essay , Proficient in the underlying principles of various technical frameworks , Recite all kinds of sql Optimization and gc principle , Of course , This is in the case of an interview , In development , Most of us have never been exposed to these , Just pretend it during the interview .
however , In order to make us feel more intuitively GC The effect , It's also a simple one for us GC Introductory cases , I use the actual code to show you the mysterious GC.
I don't know if you've known about mbean,java The code will treat all kinds of information as one by one mbean In the mbeanServer management , for example OS Information about ,jvm Memory usage , And it can be dynamically modified .
1. View the current operating system (OS) Take up memory
stay mbeanServer in ,OS The information of only corresponds to ObjectName:java.lang:type=OperatingSystem
MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
ObjectName objectName = new ObjectName("java.lang:type=OperatingSystem");
// OS Maximum memory of
Long totalPhysicalMemorySize = (Long)mBeanServer.getAttribute(objectName, "TotalPhysicalMemorySize");
// OS Of free memory
Long freePhysicalMemorySize = (Long)mBeanServer.getAttribute(objectName, "FreePhysicalMemorySize");
Long totalRAM = totalPhysicalMemorySize / 1024 / 1024;
Long freeRAM = freePhysicalMemorySize / 1024 / 1024;
System.out.println(" Total memory of operating system :" + totalRAM + " MB");
System.out.println(" The memory of the operating system is used :" + (totalRAM - freeRAM) + " MB");
2. see jvm Memory heap middle-aged and old generation
stay mbeanServer Memory pool ObjectName With java.lang:type=MemoryPool start
It can be used * To match all the jvm Memory pool , Including what we are familiar with Old age 、 The younger generation (Eden District ,survivor District )、 Meta space 、 Code cache, etc .
Acquired CompositeDataSupport yes MXBean The type of , It contains attributes max、used、init、commited
MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
ObjectName objectName = new ObjectName("java.lang:type=MemoryPool,*");
Set<ObjectInstance> memoryPools = mBeanServer.queryMBeans(objectName, null);
for (ObjectInstance memoryPool : memoryPools) {
ObjectName objectName = memoryPool.getObjectName();
String name = (String)mBeanServer.getAttribute(objectName, "Name");
CompositeDataSupport cd = (CompositeDataSupport)mBeanServer.getAttribute(objectName, "Usage");
}
3. Complete example
The description in the code is very detailed , Just look at it :
Direct operation main Method ,
Code logic :
- To look at first main Method used in the basic operation jvm Memory
- Make a statement List, Put in the data , That is, some jvm Of memory ( Let's start with the younger generation , When memory is insufficient, transfer to the old age )
- Then check the occupied jvm Memory
- hold List Remove the reference to , Again gc
- Then check the occupied jvm Memory ( By this time, I have already LIst The memory garbage occupied by data is recycled )
public class TestGc {
static List<Integer> list;
static MBeanServer mBeanServer;
static ObjectName os_objectName;
static ObjectName mp_objectName;
static{
// obtain mbeanServer
mBeanServer = ManagementFactory.getPlatformMBeanServer();
try {
// jvm When running, information such as operating system memory will be put into mBeanServer,ObjectName The only correspondence is :java.lang:type=OperatingSystem
os_objectName = new ObjectName("java.lang:type=OperatingSystem");
// stay java8 Of mBeanServer Memory pool MBean Of ObjectName With java.lang:type=MemoryPool start
mp_objectName = new ObjectName("java.lang:type=MemoryPool,*");
} catch (MalformedObjectNameException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws Exception {
osRAM();
System.out.println("main After method startup ,jvm Memory heap usage of the younger and older generations :");
jvmRAM();
list = new ArrayList<>();
for (int i = 0; i < 10000000; i++) {
list.add(i);
}
System.out.println("new Out List And put the data ,jvm Memory heap usage of the younger and older generations :");
jvmRAM();
list = null; // If you don't cancel the reference here , Even call gc It won't recycle list Memory footprint
System.gc();
System.out.println(" Cancel List References to , perform gc after ,jvm Memory heap usage of the younger and older generations :");
jvmRAM();
}
public static void osRAM() throws Exception {
// OS Maximum memory of
Long totalPhysicalMemorySize = (Long)mBeanServer.getAttribute(os_objectName, "TotalPhysicalMemorySize");
// OS Of free memory
Long freePhysicalMemorySize = (Long)mBeanServer.getAttribute(os_objectName, "FreePhysicalMemorySize");
Long totalRAM = totalPhysicalMemorySize / 1024 / 1024;
Long freeRAM = freePhysicalMemorySize / 1024 / 1024;
System.out.println(" Total memory of operating system :" + totalRAM + " MB");
System.out.println(" The memory of the operating system is used :" + (totalRAM - freeRAM) + " MB");
System.out.println("----------------------------------------------------");
}
public static void jvmRAM() throws Exception {
// jvm The young generation and the old generation
long eden = 0;
long survivor = 0;
long old = 0;
Set<ObjectInstance> memoryPools = mBeanServer.queryMBeans(mp_objectName, null);
for (ObjectInstance memoryPool : memoryPools) {
ObjectName objectName = memoryPool.getObjectName();
String name = (String)mBeanServer.getAttribute(objectName, "Name");
CompositeDataSupport cd = (CompositeDataSupport)mBeanServer.getAttribute(objectName, "Usage");
if(cd != null){
if("PS Eden Space".equals(name)){
eden = (Long) cd.get("used");
}else if("PS Survivor Space".equals(name)){
survivor = (Long) cd.get("used");
}else if("PS Old Gen".equals(name)){
old = (Long) cd.get("used");
}
}
}
System.out.println(" The younger generation :" + (eden + survivor) / 1024 / 1024 + " MB [eden " + eden / 1024 / 1024 + " MB + survivor " + survivor / 1024 / 1024 + " MB]");
System.out.println(" Old age :" + old / 1024 / 1024 + " MB");
System.out.println("----------------------------------------------------");
}
}
summary
Welcome to point out my mistake !
边栏推荐
- STM32 external interrupt experiment
- Learning C language from scratch -- installation and configuration of 01 MinGW
- QT sub window is blocked, and the main window cannot be clicked after the sub window pops up
- Global KYC service provider advance AI in vivo detection products have passed ISO international safety certification, and the product capability has reached a new level
- 1300. sum of varied array closed to target
- 文件系统中的目录与切换操作
- Project cost management__ Cost management technology__ Article 7 completion performance index (tcpi)
- Nodemcu-esp8266 development (vscode+platformio+arduino framework): Part 3 --blinker_ MIOT_ Light (lighting technology app control + Xiaoai classmate control)
- STM32 serial port usart1 routine
- Error output redirection
猜你喜欢
MySQL data manipulation language DML common commands
Fundamentals of Electronic Technology (III)__ Fundamentals of circuit analysis__ Basic amplifier operating principle
PolyWorks script development learning notes (III) -treeview advanced operation
Learning C language from scratch -- installation and configuration of 01 MinGW
UCI and data multiplexing are transmitted on Pusch (Part VI) -- LDPC coding
Project cost management__ Topic of comprehensive calculation
[combinatorics] Introduction to Combinatorics (combinatorial thought 2: mathematical induction | mathematical induction promotion | multiple induction thought)
Nr-prach: access scenario and access process
数字身份验证服务商ADVANCE.AI顺利加入深跨协 推进跨境电商行业可持续性发展
MySQL environment variable configuration
随机推荐
端午节快乐!—— canvas写的粽子~~~~~
Nr-prach: access scenario and access process
Vector processor 9_ Basic multilevel interconnection network
[CSDN]C1訓練題解析_第三部分_JS基礎
[22 graduation season] I'm a graduate yo~
[combinatorics] Introduction to Combinatorics (context of combinatorics | skills of combinatorics | thought of combinatorics 1: one-to-one correspondence)
【顺利毕业】[1]-游览 [学生管理信息系统]
Development of electrical fire system
Global KYC service provider advance AI in vivo detection products have passed ISO international safety certification, and the product capability has reached a new level
The third paper of information system project manager in soft examination
Intelligent home design and development
Leetcode daily question (931. minimum falling path sum)
Fundamentals of Electronic Technology (III)__ Chapter 6 combinational logic circuit
Nodemcu-esp8266 development board to build Arduino ide development environment
Stm32-hal library learning, using cubemx to generate program framework
Nodemcu-esp8266 development (vscode+platformio+arduino framework): Part 1 -- establishment of engineering template -template
1300. sum of varied array closed to target
MySQL Data Definition Language DDL common commands
DSP data calculation error
MySQL data manipulation language DML common commands