简体   繁体   English

从代码监视内存使用情况

[英]Monitoring memory usage from the code

We are working on a Java based product which is deployed by our customers in production. 我们正在开发基于Java的产品,由我们的客户在生产中部署。 There is a requirement that when the Java heap memory reaches a particular threshold, we should dump a line in the log file. 需要当Java堆内存达到特定阈值时,我们应该在日志文件中转储一行。 Since the product is deployed at customer site in production, we cannot use any external tools or profiles. 由于产品部署在生产中的客户现场,因此我们无法使用任何外部工具或配置文件。 The only option is to do it programmatically from the code. 唯一的选择是从代码中以编程方式执行。 I am thinking of implementing a thread that will sleep within intervals and call the Runtime.getRuntime().freeMemory() and based on the output will write to the logs. 我正在考虑实现一个将在间隔内休眠并调用Runtime.getRuntime()。freeMemory()的线程,并根据输出将写入日志。 However, I wanted to know if there is any other better approach/better APIs that we can use for this. 但是,我想知道是否还有其他更好的方法/更好的API可供我们使用。

I'd use the MemoryMXBean myself. 我自己使用MemoryMXBean It can even provide notifications of the sort you described (heap threshold exceeded). 它甚至可以提供您描述的排序通知(超出堆阈值)。 This sample code is lifted directly from the Javadoc: 示例代码直接从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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM