Java程序可以检测到它的堆空间不足吗? [英] Can a Java program detect that it's running low on heap space?

查看:66
本文介绍了Java程序可以检测到它的堆空间不足吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

整个周末,我将在室友的计算机上运行一种遗传算法,恐怕这种长期运行可能会耗尽内存.但是,我的算法以某种方式工作,可以相当容易地修剪不太有用的结果,因此,如果有一种方法可以告诉我程序何时将要用完堆空间,那么我可能可以腾出空间并继续进行下去还有一些时间.

I will be running a genetic algorithm on my roommate's computer for the whole weekend, and I'm afraid that it could run out of memory over such a long run. However, my algorithm works in such a way that would make it reasonably easy to trim less useful results, so if there was a way to tell when my program is about to run out of heap space, I could probably make room and keep going for some more time.

在OutOfMemoryError发生之前,是否有一种方法可以通知JVM堆空间不足?

Is there a way to be notified when the JVM is running out of heap space, before the OutOfMemoryError?

推荐答案

您可以注册一个javax.management.NotificationListener,当达到某个阈值时将调用它.

You can register a javax.management.NotificationListener that is called when a certain threshold is hit.

类似

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);

  }
}

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

Where listener is your own implementation of NotificationListener.

这篇关于Java程序可以检测到它的堆空间不足吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆