通过代码监视内存使用情况



我们正在开发一种基于Java的产品,该产品由我们的客户在生产中部署。有一个要求是,当Java堆内存达到特定阈值时,我们应该在日志文件中转储一行。由于产品在生产中部署在客户现场,我们不能使用任何外部工具或配置文件。唯一的选择是通过代码进行编程。我正在考虑实现一个线程,该线程将在一定时间间隔内休眠,并调用Runtime.getRuntime().freeMemory(),并根据输出写入日志。然而,我想知道是否还有其他更好的方法/更好的API可以用于此。

我会自己使用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);

最新更新