Skip to content

Instantly share code, notes, and snippets.

@zhugw
Created January 27, 2016 02:38
Show Gist options
  • Save zhugw/d07d3764b252b52ab4c3 to your computer and use it in GitHub Desktop.
Save zhugw/d07d3764b252b52ab4c3 to your computer and use it in GitHub Desktop.
模拟异常对象过多导致频繁FullGC
//如何模拟异常堆栈占用内存过多导致频繁FulGC
//java.lang.StackTraceElement数据已经占用了85M
//目前的代码不能很好的重现该问题
package com.hlj.test;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.apache.log4j.Logger;
/**
* 启动参数: -Xmx8m -Xms8m -XX:NewSize=2m -XX:MaxNewSize=2m -XX:+PrintGCDetails
* 参考文档: https://docs.oracle.com/cd/E13222_01/wls/docs81/perform/JVMTuning.html#1110613
https://docs.oracle.com/cd/E13222_01/wls/docs81/perform/JVMTuning.html
*/
public class FullGCByLogTest {
private static final Logger log = Logger.getLogger(FullGCByLogTest.class);
public static final byte[] _4M = new byte[4 * 1024 * 1024];
public static List<Exception> list = new ArrayList<>();
public static void main(String[] args) throws InterruptedException {
int nThreads = 1200; // 并发数
ExecutorService pool = Executors.newFixedThreadPool(nThreads);
final CountDownLatch latch = new CountDownLatch(nThreads);
for (int i = 0; i < nThreads; i++) {
pool.submit(new Runnable() {
@Override
public void run() {
latch.countDown();
try {
latch.await(); // 尽量等待一同执行
} catch (InterruptedException e1) {
}
while (true) {
try {
int i = 1 / 0;
System.out.println(i);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
}
}
});
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment