当前位置:网站首页>JVM garbage collection -- how to determine whether an object is garbage
JVM garbage collection -- how to determine whether an object is garbage
2022-07-18 04:17:00 【Xiao Zhao, who is working hard for millions of annual salary】
List of articles
I've learned JVM Memory model , I understand JVM Abstract the memory it manages into memory working areas with different functions , This area is continuous , Then it is divided into five parts , Attend to each one's own duties .
link : JVM Memory model —— Characteristics and functions of runtime data area
Now? , Let's learn about JVM The play in , garbage collection
Want to recycle an object as garbage , We need to know , Objects that are not needed and used are garbage , The key is how to find these objects that are not needed and used .
Here we have two methods to determine whether an object is garbage :
1 Reference counting
For an object, I make a reference count , Suppose an object currently has three references to , Then record a quotation number for him 3. Next, if a reference disappears , Become two , Another reference disappears into a , Finally, when all references disappear, the number becomes zero , When it becomes zero , This object becomes garbage (Python Is to use this way ).
summary :
If an object has no reference to it , Or the value in the reference counter is 0 When , Indicates that the object is garbage .
defects : When there is a circular reference , As a result, objects that should be garbage cannot be recycled .
that Java Is this a garbage collection method used ?
Take a chestnut :
public class ReferenceCountingGC {
public Object instance = null;
private static final int _1MB = 1024 * 1024;
/** * The only meaning of this member property is to occupy memory , In order to be able to GC Check the log to see if there is any recycling * */
private byte[] bigSize = new byte[2 * _1MB];
public static void testGC() {
ReferenceCountingGC objA = new ReferenceCountingGC();
ReferenceCountingGC objB = new ReferenceCountingGC();
objA.instance = objB;
objB.instance = objA;
objA = null;
objB = null;
// Suppose it happens in this line GC,objA and objB Can it be recycled ?
System.gc();
}
public static void main(String[] args) {
testGC();
}
}
Run a screenshot :
As can be seen from the above figure , Before garbage collection , Memory footprint 11960K. After garbage collection , Memory footprint 896K. It indicates that the object is indeed recycled and released . But if you follow the reference counting algorithm , In fact, there are mutual references between the two objects , That is, the value of the reference counter is 1, That is to say, it should not be recycled , So the reference counting algorithm is obviously not used here .
2 Accessibility analysis
Java It's using a method called GC Root The algorithm of , What does that mean ?
Find the object from the reference on the root , Objects that can be referenced by the root node are not garbage , Don't recycle , If you reference objects that cannot be found from the root node, they are garbage .
adopt GC Root The object of , Start looking down , See if an object can reach
Be able to act as GC Root: Class loader 、Thread、 Local variable table of virtual machine stack 、static member 、 const reference 、 Variables of local method stack, etc .
JVM The following are given in the standard as GC Root The object of :
1. In the virtual machine stack ( Local variables in stack frames ) Object referenced in , For example, the parameters used in the method stack that each thread is called 、 local variable 、 Temporary variables, etc .
2. Objects referenced by class static properties in method area , for example Java Class reference type static variable .
3. Objects referenced by constants in the method area , For example, string constant pool (String Table) Quote from .
4. In the local method stack JNI( That is what is usually said Native Method ) Referenced object .
5.Java References inside the virtual machine , For example, the basic data type corresponds to Class object , Some resident exception objects ( such as NullPointExcepiton、OutOfMemoryError) etc. , And the system class loader .
6. All are locked in sync (synchronized keyword ) The object of holding .
7. reflect Java What's going on inside the virtual machine JMXBean、JVMTI Callback registered in 、 Local code cache, etc .
We have been studying how to make an object die , however
3 Does an object really have to die ?
3.1 The self salvation of the object
Even unreachable objects in the reachability analysis algorithm , Not at all ” Must die “, To actually declare an object dead , At least experience Twice marking The process :
- If the object is found to have no relationship with GCRoots Linked reference chain , Then it will be tagged for the first time and screened , The condition for filtering is whether the object is necessary to execute finalize() Method .
- When the object is not overridden finalize() Method , or finalize() Method has been called by the virtual machine .
Virtual machines see both as ” No need to implement “.
If this object is determined to be necessary to execute finalize() Method , So this object will be placed in a place called F-Queue In the queue of , And later created automatically by a virtual machine 、 Low priority Of Finalizer Thread to execute it .
The so-called “ perform ” It means that the virtual opportunity triggers this method , But it doesn't promise to wait for it to run , And the reason for that is , If an object is in finalize() Slow execution in method , Or there's a dead cycle ( In more extreme cases ), Will probably lead to F-Queue Other objects in the queue are permanently waiting , It even causes the whole memory recycling system to crash .
finalize() The method is the last chance for the object to escape death , later GC Will be right F-Queue The objects in are marked a second time on a small scale , If the object is to be finalize() To save yourself —— Just re associate with any object in the reference chain , For example, we should (this keyword ) Assign to a class variable or a member variable of an object , Then it will be removed at the second time “ About to be recycled ” Set ; If the object hasn't escaped yet , So basically it's really recycled .
3.2finalize The role of
- finalize() yes Object Of protected Method , Subclasses can override this method for resource cleanup ,GC Call this method before recovering objects. .
- finalize() And C++ The destructor in does not correspond to .C++ The timing of the destructor call in is determined ( Object out of scope or delete fall ), but Java Medium finalize The call to has uncertainty
- Not recommended for use finalize Method to complete “ Non memory resources ” Clean-up work .
3.3finalized The problem of
- Some with finalize Related methods , Because of some fatal defects , It has been abandoned , Such as System.runFinalizersOnExit() Method 、Runtime.runFinalizersOnExit() Method
- System.gc() And System.runFinalization() Methods added finalize Opportunities for method execution , But don't rely on them blindly
- Java Language norms do not guarantee finalize Methods will be implemented in a timely manner 、 And there's no guarantee that they'll be implemented
- finalize Methods can cause performance problems . because JVM Usually done in a separate low priority thread finalize Implementation
- Object regeneration problem :finalize In the method , The object to be recycled can be assigned to GC Roots Accessible object references , So as to achieve the purpose of object regeneration
- finalize The method is at best by GC Do it once ( Of course, users can call objects by hand finalize Method , But it doesn't affect GC Yes finalize act )
because Finalizer The priority of threads is lower than that of ordinary threads , According to the Java Preemptive thread scheduling strategy , The lower priority thread , Distribute CPU The less opportunities , So when multithreading creates overrides finalize Method object ,Finalizer May not be able to execute in time finalize Method ,Finalizer When the speed of the thread recycling objects is less than the speed of creating objects , Can cause F-Queue More and more big ,JVM Memory cannot be released in time , Cause frequent Young GC, And then there was Full GC, And finally OutOfMemoryError.
3.4finalize Implementation process of ( Life cycle )
First , Give a general description of finalize technological process : When the object becomes (GC Roots) Unreachable time ,GC It will determine whether the object covers finalize Method , If not covered , Then recycle it directly . otherwise , If the object has not been executed finalize Method , Put it in the F-Queue queue , The... Of the objects in the queue is executed by a low priority thread finalize Method . perform finalize After the method ,GC Whether the object is reachable will be judged again , If you can't reach , Then recycle , otherwise , object “ resurrection ”.
Execute code demo :
public class FinalizeEscapeGC {
public static FinalizeEscapeGC SAVE_HOOK = null;
public void isAlive() {
System.out.println("yes, i am still alive :)");
}
@Override
protected void finalize() throws Throwable {
super.finalize();
System.out.println("finalize method executed!");
FinalizeEscapeGC.SAVE_HOOK = this;
}
public static void main(String[] args) throws Throwable {
SAVE_HOOK = new FinalizeEscapeGC();
// The object successfully saved himself for the first time
SAVE_HOOK = null;
System.gc();
// because Finalizer Method priority is very low , Pause 0.5 second , To wait for it
Thread.sleep(500);
if (SAVE_HOOK != null) {
SAVE_HOOK.isAlive();
} else {
System.out.println("once, i am dead :(");
}
// The following code is exactly the same as the one above , But the self rescue failed this time
SAVE_HOOK = null;
System.gc();
// because Finalizer Method priority is very low , Pause 0.5 second , To wait for it
Thread.sleep(500);
if (SAVE_HOOK != null) {
SAVE_HOOK.isAlive();
} else {
System.out.println("second, i am dead :(");
}
}
}

It can be seen from the results ,SAVE_HOOK Object's finalize() The method is indeed used GC The collector has triggered , And managed to escape before being collected .
Another noteworthy thing is , There are two identical pieces of code in the code , The execution turned out to be an escape , A failure , It's because of any object finalize() Methods are called only once by the system , If the object is facing the next recycle , its finalize() Method will not be executed again , So the self rescue operation of the second code failed .
边栏推荐
- Ant begin opens PDF to add authentication parameter data
- Machine learning - matrix derivation basic formula + common formula
- flink的yarn集群方式(1)
- 最大子段和+线段树.1
- Midnight - customized version of Excel office automation
- 创意丝带样式登录页面
- Blue Bridge Cup VIP question bank
- ZCMU--1098: 查找元素
- JS image clipping and compression integration plug-in
- leetcode 605. Can place flowers planting problem (simple)
猜你喜欢

Good news | the scores of candidates in this area can be queried

JS figure guess fruit and vegetable games code

101. (cesium chapter) cesium particle system - snow

JVM内存模型——运行时数据区的特点和作用

js看图猜水果蔬菜小游戏代码

Flat rider registration form

从源码探究双亲委派机制

Machine learning - matrix derivation basic formula + common formula

Gavin wood, founder of Poka: what will happen to Poka governance V2?

101.(cesium篇)cesium粒子系统-下雪
随机推荐
最大子段和+线段树.1
ant-desgin 打開pdf增加認證參數據
MIMX8MD6CVAHZAB I.MX 8MDUAL Cortex-A53 - 微处理器
Technology sharing | send requests using postman
MySQL8.0学习记录18 - Tablespaces
10分钟带你进入Swagger的世界,快来看一看吧
40+倍提升,详解 JuiceFS 元数据备份恢复性能优化之路
Lingyun going to sea | Lianlian International & Huawei cloud: building a cross-border e-commerce digital service network
盘点波卡生态潜力项目 | 跨链特性促进多赛道繁荣
Unity engineering manages Pico and oculus projects in a unified manner
tab加swiper长列表滚动
JS figure guess fruit and vegetable games code
mysql 传入List<String>进行查询的方法
强化学习(Q-Learning)与路径搜索(A*)的联系
[vuforia] some test records of vuforia plug-ins (3D object recognition and ground recognition)
响应式用户登录表单
ant-desgin 打开pdf增加认证参数据
JVM垃圾收集—垃圾收集器及常见组合参数
技术分享 | 抓包分析 TCP 协议
On the difference and use of hash and history