如何捕获子线程里面的OOM?
如何捕获子线程里面的OOM?
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryMXBean;
import java.lang.management.MemoryUsage;
public class Main extends Thread {
private static final int MEGABYTE = (1024 * 1024);
public void run() {
for (int i = 1; i <= 100; i++) {
byte[] bytes = new byte[MEGABYTE * 500];
}
}
public static void main(String args[]) {
MemoryMXBean memoryBean = ManagementFactory.getMemoryMXBean();
try {
(new Main()).start();
} catch (Exception e) {
e.printStackTrace();
} catch (OutOfMemoryError e) {
MemoryUsage heapUsage = memoryBean.getHeapMemoryUsage();
long maxMemory = heapUsage.getMax() / MEGABYTE;
long usedMemory = heapUsage.getUsed() / MEGABYTE;
System.out.println(" : Memory Use :" + usedMemory + "M/" + maxMemory + "M");
}
}
}