【问题标题】:Notification of memory shortage in JavaJava中内存不足的通知
【发布时间】:2011-09-03 17:41:42
【问题描述】:

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);

【问题讨论】:

  • @Andy 这就是我阅读 Javadoc 的结果。没有经过全面测试,但想法就在那里......
  • 请注意,当超过内存使用阈值时,此代码会通知您...但是您仍然需要设置阈值。这必须为每个现有的内存池完成。
  • 另外,下次您找到问题的可能解决方案时,请将其作为答案发布,而不是在问题中包含解决方案代码。

标签: java memory listener threshold


【解决方案1】:

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

【讨论】:

  • +1 我本来打算在OutOfMemoryError 上建议try/catch 并采取一些安全措施,但人们总是抱怨我甚至提到抓捕的“异端”一个Error。 ;)
  • @Andrew 我想提出同样的建议,但后来我看到了@Andy 的答案。对此答案 +1。
  • @Andrew,可以捕捉到OutofMemoryError(我之前也做过),但是在不中断程序流程的情况下处理好Error 非常困难。
  • @notnoop:我的策略是在一个大的byte[]nulled 之后弹出一个JOptionPane,所以它肯定“中断程序的流程”就用户输入而言!
  • 您可能还想在抛出 OutOfMemoryError 时捕获堆转储。在 Hotspot 上,-XX:+HeapDumpOnOutOfMemoryError 开关可以做到这一点。转储可以导入 VisualVM 并帮助您稍后分析问题。 oracle.com/technetwork/java/javase/memleaks-137499.html#gdyrr
猜你喜欢
  • 2019-06-28
  • 1970-01-01
  • 1970-01-01
  • 2013-10-23
  • 2012-06-21
  • 2013-09-10
  • 2012-12-12
  • 2017-07-19
  • 1970-01-01
相关资源
最近更新 更多