【发布时间】: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