Out of memory notification in Java

Is there any shipped function in Java that notifies you of insufficient memory in the application (or a notification that it has reached a given level)?

I was wondering if it is possible to register a listener somewhere (or something like that)? I know about memory methods in the Runtime class. I could create a planned task to check the remaining memory on my own, but I wonder if an existing solution exists.

I don’t think so, but I’m looking for confirmation.

FOR RECORDING

MemoryMXBean mbean = ManagementFactory.getMemoryMXBean(); NotificationEmitter emitter = (NotificationEmitter) mbean; NotificationListener listener = new NotificationListener() { @Override public void handleNotification(Notification notif, Object handback) { String notifType = notif.getType(); if (notifType.equals(MemoryNotificationInfo.MEMORY_THRESHOLD_EXCEEDED) || notifType.equals(MemoryNotificationInfo.MEMORY_COLLECTION_THRESHOLD_EXCEEDED)) { // Retrieve the memory notification information CompositeData cd = (CompositeData) notif.getUserData(); MemoryNotificationInfo info = MemoryNotificationInfo.from(cd); MemoryUsage mu = info.getUsage(); System.out.println("Maximum memory = " + mu.getMax()); System.out.println("Used memory = " + mu.getUsed()); } } }; emitter.addNotificationListener(listener, null, null); 
+7
source share
1 answer

I believe that you can configure the listener for the memory usage threshold using MemoryMXBean . Sample code is provided in the javadoc link.

+5
source

All Articles