Java中内存不足的通知
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);
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);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我相信您可以使用 MemoryMXBean。 javadoc 链接中提供了示例代码。
I believe you can set up a listener for a memory usage threshold using the MemoryMXBean. Sample code is provided in the javadoc link.