Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Notification of memory shortage in Java

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);
like image 437
Jérôme Verstrynge Avatar asked May 27 '11 22:05

Jérôme Verstrynge


1 Answers

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

like image 51
Andy Avatar answered Oct 07 '22 13:10

Andy