【问题标题】:Monitoring memory usage from the code从代码监控内存使用情况
【发布时间】:2013-01-31 08:55:33
【问题描述】:
我们正在开发一种基于 Java 的产品,该产品由我们的客户在生产中部署。要求当 Java 堆内存达到特定阈值时,我们应该在日志文件中转储一行。由于产品在生产中部署在客户现场,我们不能使用任何外部工具或配置文件。唯一的选择是从代码中以编程方式进行。我正在考虑实现一个线程,该线程将在间隔内休眠并调用 Runtime.getRuntime().freeMemory() 并根据输出写入日志。但是,我想知道是否有其他更好的方法/更好的 API 可以用于此目的。
【问题讨论】:
标签:
java
jakarta-ee
memory-management
profiling
heap-memory
【解决方案1】:
我自己会使用MemoryMXBean。它甚至可以提供您描述的那种通知(超出堆阈值)。此示例代码直接取自 Javadoc:
class MyListener implements javax.management.NotificationListener {
public void handleNotification(Notification notif, Object handback) {
// handle notification
....
}
}
MemoryMXBean mbean = ManagementFactory.getMemoryMXBean();
NotificationEmitter emitter = (NotificationEmitter) mbean;
MyListener listener = new MyListener();
emitter.addNotificationListener(listener, null, null);