import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.lang.management.ManagementFactory; import java.lang.management.MemoryMXBean; import java.lang.management.MemoryPoolMXBean; import java.lang.management.MemoryNotificationInfo; import java.lang.management.MemoryUsage; import java.util.List; import javax.management.Notification; import javax.management.NotificationEmitter; import javax.management.NotificationListener; import javax.management.openmbean.CompositeData; import javax.swing.JButton; import javax.swing.JOptionPane; public class MemoryNotificationTest extends MemoryPoolMXBeanTest { public MemoryNotificationTest(long usageThreshold, long collectionUsageThreshold) { super(); JButton gcButton = new JButton("GC"); gcButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { gc(); } }); panel.add(gcButton); panel.revalidate(); System.out.println(usageThreshold); System.out.println(collectionUsageThreshold); NotificationListener listener = new NotificationListener() { public void handleNotification(Notification notification, Object handback) { String type = notification.getType(); if (type.equals(MemoryNotificationInfo.MEMORY_THRESHOLD_EXCEEDED) || type.equals(MemoryNotificationInfo.MEMORY_COLLECTION_THRESHOLD_EXCEEDED)) { CompositeData cd = (CompositeData)notification.getUserData(); MemoryNotificationInfo info = MemoryNotificationInfo.from(cd); String poolName = info.getPoolName(); long count = info.getCount(); MemoryUsage usage = info.getUsage(); String message = "Type : " + type + "\nMemory Pool Name: " + poolName + "\nUsage: " + createUsageText(usage); JOptionPane.showMessageDialog(frame, message, "Memory Warning", JOptionPane.WARNING_MESSAGE); } } }; MemoryMXBean mbean = ManagementFactory.getMemoryMXBean(); NotificationEmitter emitter = (NotificationEmitter)mbean; emitter.addNotificationListener(listener, null, null); List pools = ManagementFactory.getMemoryPoolMXBeans(); for (MemoryPoolMXBean pool: pools) { if (pool.getName().indexOf("Tenured") != -1) { pool.setUsageThreshold(usageThreshold); pool.setCollectionUsageThreshold(collectionUsageThreshold); break; } } } private void gc() { MemoryMXBean mbean = ManagementFactory.getMemoryMXBean(); mbean.gc(); updateInfoTab(); } public static void main(String[] args) { long usageThreshold = Long.parseLong(args[0]); long collectionUsageThreshold = Long.parseLong(args[1]); new MemoryNotificationTest(usageThreshold, collectionUsageThreshold); } }