从代码监视内存使用情况

时间:2013-02-15 11:30:31

标签: java java-ee memory-management profiling heap

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

1 个答案:

答案 0 :(得分:2)

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