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