We are working on a Java based product which is deployed by our customers in production. There is a requirement that when the Java heap memory reaches a particular threshold, we should dump a line in the log file. 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. However, I wanted to know if there is any other better approach/better APIs that we can use for this.
1 Answer
I'd use the MemoryMXBean myself. It can even provide notifications of the sort you described (heap threshold exceeded). This sample code is lifted directly from the 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);