zneak
zneak

Reputation: 138251

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

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?

Upvotes: 11

Views: 2993

Answers (4)

henry
henry

Reputation: 6106

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.

Upvotes: 8

Shashank Kadne
Shashank Kadne

Reputation: 8101

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

Upvotes: 0

user207421
user207421

Reputation: 311055

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

Upvotes: 2

Nikhil
Nikhil

Reputation: 3152

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

Upvotes: 3

Related Questions