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

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

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

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

就像是

final MemoryMXBean memBean = ManagementFactory.getMemoryMXBean(); final NotificationEmitter ne = (NotificationEmitter) memBean; ne.addNotificationListener(listener, null, null); final List 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实现。

你可以试试这个:

 // 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

只需将WeakReferences用于可丢弃的结果,如果出于空间原因,它们将被丢弃。

我不确定这个,但JConsole不能解决你的目的吗?