在垃圾回收的时候(特别是 FULL GC)会对应用程序造成停顿
代码
构造 2 个 线程,一个应用程序打印(每 0.1 秒输出一次),一个是制造 GC 的线程,查看 StopTheWorld 现象
package com.mousycoder.mycode.thinking_in_jvm;
import java.util.HashMap;
/**
* @version 1.0
* @author: mousycoder
* @date: 2019-07-09 17:41
*/
public class StopWorldTest {
public static class MyThread extends Thread {
HashMap map = new HashMap();
@Override
public void run() {
while (true) {
try {
if (map.size() * 512/1024/1024 >= 800) {
map.clear();
}
byte [] b1;
for (int i = 0; i < 100; i++) {
b1 = new byte[512];
map.put(System.nanoTime(),b1);
}
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public static class PrintThread extends Thread {
public static final long starttime = System.currentTimeMillis();
@Override
public void run() {
while (true) {
try {
long t = System.currentTimeMillis() - starttime;
System.out.println(t / 1000 + " ." + t % 1000);
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
MyThread t = new MyThread();
PrintThread p = new PrintThread();
t.start();
p.start();
}
}
输出:
100 .322 100 .428 100 .533 101 .697 101 .803 101 .906
GC 日志:
100.750: [GC (Allocation Failure) 100.750: [DefNew: 447K->63K(448K), 0.0010900 secs] 1048273K->1047974K(1048512K), 0.0011650 secs] [Times: user=0.00 sys=0.00, real=0.00 secs] 100.761: [GC (Allocation Failure) 100.761: [DefNew: 447K->447K(448K), 0.0000290 secs]100.761: [Tenured: 1047910K->111170K(1048064K), 1.1351630 secs] 1048358K->111170K(1048512K), [Metaspace: 7465K->7465K(1056768K)], 1.1353270 secs] [Times: user=0.37 sys=0.53, real=1.13 secs] 101.902: [GC (Allocation Failure) 101.902: [DefNew: 384K->45K(448K), 0.0005170 secs] 111554K->111215K(1048512K), 0.0005900 secs] [Times: user=0.00 sys=0.00, real=0.00 secs]
可以发现 100.761 秒的时候,发生了一次 FULL GC,用时1秒多,影响到应用程序输出(100 .533->101 .697 耗时 1 秒多,其他的地方都是0.1秒输出)