Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

memory

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.

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

like image 884
zneak Avatar asked Mar 16 '12 05:03

zneak


People also ask

How do I check my heap usage?

Checking Heap Usage:Sign on to the Weblogic Administration Console by entering the following URL in a browser: http://funoracle.lab:7001/console. Expand your WebLogic domain then expand Servers. Click the server you intend to monitor. Select the Monitoring tab, and the Performance sub-tab.

Can we access heap memory in Java?

Heap Memory is used for Dynamic Memory Allocation of Java objects and JRE classes that are created during the execution of a Java program. Heap memory is allocated to objects at runtime and these objects have global access which implies they can be accessed from anywhere in the application.


3 Answers

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.

like image 161
henry Avatar answered Nov 13 '22 02:11

henry


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

like image 44
Nikhil Avatar answered Nov 13 '22 00:11

Nikhil


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

like image 43
user207421 Avatar answered Nov 13 '22 01:11

user207421