gpt4 book ai didi

java - GC 如何挂起/阻塞应用程序线程

转载 作者:行者123 更新时间:2023-11-29 07:40:36 25 4
gpt4 key购买 nike

我了解当新对象分配失败或调用 System.gc() 时会触发 GC。每个 GC 算法都建议,作为第一步,GC 线程将挂起所有应用程序线程,这样它们就不会影响 GC Activity 。

但是我想了解GC是如何暂停所有正在运行的线程的?我的意思是 JVM 是否定义了任何安全点,例如,内存分配(创建新对象)或方法调用,当应用程序线程到达这些安全点时,它们将被 GC 锁阻塞。是真的吗?如果是这样,那么仅执行如下简单计算的应用程序线程如何(我知道实际上这永远不会发生),它会被挂起吗?

while(true) {
a = a + s;
s = s + a;

// some computation that doesn't touch any JVM safe points
}

在这些情况下,GC Activity 是否会在不挂起这些应用程序线程的情况下继续进行(并且稍后在它们尝试越过安全点时挂起/阻塞,例如对象分配)?

但我相信,GC总是会等待这些应用程序线程进入安全点并暂停它们,然后再继续。我的假设是真的吗?

最佳答案

But I would like to understand how GC suspends all the running threads?

热点实现使用safepoint polling .引用:

How safepoints work?

Safepoint protocol in HotSpot JVM is collaborative. Each application thread checks safepoint status and park itself in safe state in safepoint is required. For compiled code, JIT inserts safepoint checks in code at certain points (usually, after return from calls or at back jump of loop). For interpreted code, JVM have two byte code dispatch tables and if safepoint is required, JVM switches tables to enable safepoint check.

Safepoint status check itself is implemented in very cunning way. Normal memory variable check would require expensive memory barriers. Though, safepoint check is implemented as memory reads a barrier. Then safepoint is required, JVM unmaps page with that address provoking page fault on application thread (which is handled by JVM’s handler). This way, HotSpot maintains its JITed code CPU pipeline friendly, yet ensures correct memory semantic (page unmap is forcing memory barrier to processing cores).

more detailed description来自机械同情邮件列表。


 // some computation that doesn't touch any JVM safe points 

编译器只允许那些可以证明它们在有限时间内完成的事情。否则它会插入安全点轮询

关于java - GC 如何挂起/阻塞应用程序线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30690620/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com