有没有办法在 JVM 中强制/重现 FullGC x 秒?基本上我需要这个来验证某些基于心跳的应用程序(zookeeper 的客户端)中问题的根本原因
编辑:unix命令kill -STOP <pid>
和 kill -CONT <pid>
模拟 FullGC(停止世界行为)?
最佳答案
您可以在 HotSpot JVM 上模拟一个非常长的 stop-the-world 事件,从用户的角度来看,它类似于 FullGC。
HotSpot 不放 safepoints进入计数的 int 循环,因为它假定它们将“足够快”地终止(在这种情况下,服务器编译器将生成更优化的循环代码)。即使是停止世界也必须等到这个循环结束。在下面的例子中,我们有一个非常紧凑的循环,它在没有安全点轮询的情况下进行小而昂贵的计算:
public static double slowpoke(int iterations) {
double d = 0;
for (int j = 1; j < iterations; j++) {
d += Math.log(Math.E * j);
}
return d;
}
为了像暂停一样重现 FullGC,你可以使用这样的东西:
public class SafepointTest {
public static double slowpoke(int iterations) {
double d = 0;
for (int j = 1; j < iterations; j++) {
d += Math.log(Math.E * j);
}
return d;
}
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread() {
@Override
public void run() {
double sideEffect = 0;
for (int i = 0; i < 10000; i++) {
sideEffect = slowpoke(999999999);
}
System.out.println("result = " + sideEffect);
}
};
thread.start();
new Thread(){
@Override
public void run() {
long timestamp = System.currentTimeMillis();
while (true){
System.out.println("Delay " + (System.currentTimeMillis() - timestamp));
timestamp = System.currentTimeMillis();
//trigger stop-the-world
System.gc();
}
}
}.start();
thread.join();
}
}
结果:
Delay 5
Delay 4
Delay 30782
Delay 21819
Delay 21966
Delay 22812
Delay 22264
Delay 21988
为了增加延迟,只需更改 slowpoke(int iterations)
函数的参数值即可。
这是有用的诊断命令:
-XX:+PrintGCApplicationStoppedTime
这实际上会将所有安全点的暂停时间报告到 GC 日志中。不幸的是,此选项的输出缺少时间戳。-XX:+PrintSafepointStatistics –XX:PrintSafepointStatisticsCount=1
这两个选项将强制 JVM 在每个安全点后报告原因和时间。
编辑
关于编辑:从用户的角度来看,kill -STOP
和 kill -CONT
与 STW 具有相同的语义,即应用程序不响应任何请求。但是,这需要访问命令行并且不消耗资源(CPU、内存)。
关于java - 如何在 JVM 中强制/重现 Full GC?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33917951/