Java中内存不足的通知

Jér*_*nge 7 java memory listener threshold

Java中是否有任何已交付的功能通知应用程序中的内存不足(或通知它已达到预定义级别)?

我想知道是否有可能在某处注册一个听众(或类似的东西)?我知道Runtime类中的内存方法.我可以自己创建一个计划任务来检查剩余内存,但我想知道是否已经有一个现有的解决方案.

我不这么认为,但我正在寻找确认.

对于记录

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);
Run Code Online (Sandbox Code Playgroud)

And*_*ndy 6

我相信您可以使用MemoryMXBean为内存使用阈值设置监听器.示例代码在javadoc链接中提供.