我将在室友的电脑上运行一个遗传算法整个周末,我担心这么长时间会耗尽内存。不过我的算法工作方式可以相对轻松地修剪掉一些不太有用的结果,所以如果有办法在程序即将耗尽堆空间之前告诉我,我可能可以腾出空间继续运行更长时间。
在OutOfMemoryError之前是否有办法通知我当JVM快要耗尽堆空间时?
我将在室友的电脑上运行一个遗传算法整个周末,我担心这么长时间会耗尽内存。不过我的算法工作方式可以相对轻松地修剪掉一些不太有用的结果,所以如果有办法在程序即将耗尽堆空间之前告诉我,我可能可以腾出空间继续运行更长时间。
在OutOfMemoryError之前是否有办法通知我当JVM快要耗尽堆空间时?
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);
}
}
这里的listener是你自己实现的NotificationListener。
// Get current size of heap in bytes
long heapSize = Runtime.getRuntime().totalMemory();
// Get maximum size of heap in bytes. The heap cannot grow beyond this size.
// Any attempt will result in an OutOfMemoryException.
long heapMaxSize = Runtime.getRuntime().maxMemory();
// Get amount of free memory within the heap in bytes. This size will increase
// after garbage collection and decrease as new objects are created.
long heapFreeSize = Runtime.getRuntime().freeMemory();
在这里找到 - http://www.exampledepot.com/egs/java.lang/GetHeapSize.html
(该链接介绍了如何在Java中获取堆大小的方法)只需使用WeakReferences
来处理可丢弃的结果,这样如果出于空间原因需要丢弃它们,它们就会被丢弃。