HeapUsageMonitor() { int c = 0; for (MemoryPoolMXBean m : ManagementFactory.getMemoryPoolMXBeans()) { if (m.getType() != MemoryType.HEAP) // only interested in HEAP continue; if (m.isCollectionUsageThresholdSupported() && m.isUsageThresholdSupported()) { // should be Old pool, get called when memory is critical _oldGenBean = m; _gc_callback = MEM_MAX; // Really idiotic API: no idea what the usageThreshold is, so I have // to guess. Start high, catch IAE & lower by 1/8th and try again. while (true) { try { m.setCollectionUsageThreshold(_gc_callback); break; } catch (IllegalArgumentException iae) { // Do NOT log this exception, it is expected and unavoidable and // entirely handled. _gc_callback -= (_gc_callback >> 3); } } NotificationEmitter emitter = (NotificationEmitter) _allMemBean; emitter.addNotificationListener(this, null, m); ++c; } } assert c == 1; }
public static void main(String[] argv) throws Exception { memory = new ObjectName(MEMORY_MXBEAN_NAME); runtime = new ObjectName(RUNTIME_MXBEAN_NAME); thread = new ObjectName(THREAD_MXBEAN_NAME); os = new ObjectName(OPERATING_SYSTEM_MXBEAN_NAME); List<MemoryPoolMXBean> pools = getMemoryPoolMXBeans(); for (MemoryPoolMXBean p : pools) { if (heapPool == null && p.getType() == MemoryType.HEAP && p.isUsageThresholdSupported() && p.isCollectionUsageThresholdSupported()) { heapPool = new ObjectName(MEMORY_POOL_MXBEAN_DOMAIN_TYPE + ",name=" + p.getName()); } if (nonHeapPool == null && p.getType() == MemoryType.NON_HEAP && p.isUsageThresholdSupported()) { nonHeapPool = new ObjectName(MEMORY_POOL_MXBEAN_DOMAIN_TYPE + ",name=" + p.getName()); } } // Check notification emitters MyListener listener = new MyListener(); server.addNotificationListener(memory, listener, null, null); server.removeNotificationListener(memory, listener); checkEnum(); checkList(); checkMap(); checkMemoryUsage(); checkThreadInfo(); checkOS(); checkSunGC(); System.out.println("Test passed."); }