Java程序可以检测到它在堆空间上运行不足吗?

zne*_*eak 11 java memory

我会在我的室友的电脑上运行一个遗传算法整个周末,我担心它会在这么长时间内耗尽内存.但是,我的算法以这样的方式工作,这样可以很容易地减少不太有用的结果,所以如果有办法告诉我的程序什么时候用完了堆空间,我可能会腾出空间继续前进多一点时间.

在OutOfMemoryError之前,有没有办法在JVM用完堆空间时收到通知?

hen*_*nry 8

您可以注册在达到特定阈值时调用的javax.management.NotificationListener.

就像是

final MemoryMXBean memBean = ManagementFactory.getMemoryMXBean();
final NotificationEmitter ne = (NotificationEmitter) memBean;

ne.addNotificationListener(listener, null, null);

final List<MemoryPoolMXBean> memPools = ManagementFactory
    .getMemoryPoolMXBeans();
for (final MemoryPoolMXBean mp : memPools) {
  if (mp.isUsageThresholdSupported()) {
    final MemoryUsage mu = mp.getUsage();
    final long max = mu.getMax();
    final long alert = (max * threshold) / 100;
    mp.setUsageThreshold(alert);

  }
}
Run Code Online (Sandbox Code Playgroud)

监听器是您自己的NotificationListener实现.