public class GcTest {
public static void main(String[] args) {
try {
Class<?> clazz = Class.forName("sun.misc.GC");
Method requestLatency = clazz.getMethod("requestLatency", new Class[] { long.class });
requestLatency.invoke(null, 10000L);
new GcTest().new MemThread().start();
Thread.sleep(1000000L);
} catch (ClassNotFoundException e) {
} catch (Exception e) {
}
}
class MemThread extends Thread{
@Override
public void run(){
while(true){
{
Random r = new Random();
int i = r.nextInt(100);
System.out.println("create mem :"+i+"MB");
int size = i * 1024 * 1024;
byte[] bytes = new byte[size];
}
try {
Thread.sleep(2000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
手动设置代码GC频率为10s,然后创建异步线程进行随机内存空间开辟,通过监控看到内存回收情况。