1 10 package mondrian.util; 11 12 import java.lang.management.MemoryMXBean ; 13 import java.lang.management.MemoryNotificationInfo ; 14 import java.lang.management.MemoryUsage ; 15 import java.lang.management.ManagementFactory ; 16 import java.lang.management.MemoryPoolMXBean ; 17 import java.lang.management.MemoryType ; 18 import javax.management.Notification ; 19 import javax.management.NotificationEmitter ; 20 import javax.management.NotificationListener ; 21 import org.apache.log4j.Logger; 22 23 42 public class NotificationMemoryMonitor extends AbstractMemoryMonitor { 43 private static final Logger LOGGER = 44 Logger.getLogger(NotificationMemoryMonitor.class); 45 46 47 protected static final MemoryPoolMXBean TENURED_POOL; 48 49 static { 50 TENURED_POOL = findTenuredGenPool(); 51 } 52 53 private static MemoryPoolMXBean findTenuredGenPool() { 54 for (MemoryPoolMXBean pool : ManagementFactory.getMemoryPoolMXBeans()) { 55 if (pool.getType() == MemoryType.HEAP && 58 pool.isUsageThresholdSupported()) { 59 return pool; 60 } 61 } 62 throw new AssertionError ("Could not find tenured space"); 63 } 64 65 72 private class NotificationHandler implements NotificationListener { 73 74 82 public void handleNotification(final Notification notification, 83 final Object unused) { 84 final String type = notification.getType(); 85 86 if (type.equals(MemoryNotificationInfo.MEMORY_THRESHOLD_EXCEEDED)) { 87 final MemoryUsage usage = TENURED_POOL.getUsage(); 88 89 notifyListeners(usage.getUsed(), usage.getMax()); 90 } 91 } 92 } 93 94 95 99 NotificationMemoryMonitor() { 100 super(); 101 final MemoryMXBean mbean = ManagementFactory.getMemoryMXBean(); 102 final NotificationEmitter emitter = (NotificationEmitter ) mbean; 103 104 emitter.addNotificationListener(new NotificationHandler(), null, null); 106 } 107 108 113 protected Logger getLogger() { 114 return LOGGER; 115 } 116 117 123 protected void notifyNewLowThreshold(final long newLowThreshold) { 124 125 if (newLowThreshold == Long.MAX_VALUE) { 126 TENURED_POOL.setUsageThreshold(0); 127 } else { 128 TENURED_POOL.setUsageThreshold(newLowThreshold); 129 } 130 } 131 132 137 public long getMaxMemory() { 138 return TENURED_POOL.getUsage().getMax(); 139 } 140 145 public long getUsedMemory() { 146 return TENURED_POOL.getUsage().getUsed(); 147 } 148 } 149 150 | Popular Tags |