Is there any delivered feature in Java notifying a memory shortage in an application (or notifying that it has reach a predefined level)?
I was wondering whether it was possible to register a listener (or something equivalent) somewhere? I know about the memory methods in the Runtime class. I could create a scheduled task checking remaining memory myself, but I am wondering whether there is already an existing solution.
I don't think so, but I am looking for a confirmation.
FOR THE RECORDS
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);