Can a Java program detect that it's running low on heap space?

前端 未结 4 2149
故里飘歌
故里飘歌 2021-01-04 12:00

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 alg

相关标签:
4条回答
  • 2021-01-04 12:24

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

    Something like

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

    Where listener is your own implementation of NotificationListener.

    0 讨论(0)
  • 2021-01-04 12:33

    Just use WeakReferences for the discardable results, then they will be discarded if necessary for space reasons.

    0 讨论(0)
  • 2021-01-04 12:35

    You can try this:

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

    As found here - http://www.exampledepot.com/egs/java.lang/GetHeapSize.html

    0 讨论(0)
  • 2021-01-04 12:38

    I am not sure about this, but can't JConsole solve your purpose ??

    0 讨论(0)
提交回复
热议问题