001    package railo.commons.management;
002    
003    import java.lang.management.ManagementFactory;
004    import java.lang.management.MemoryMXBean;
005    import java.lang.management.MemoryPoolMXBean;
006    import java.lang.management.MemoryType;
007    import java.util.HashMap;
008    import java.util.Map;
009    
010    import javax.management.NotificationEmitter;
011    
012    import railo.runtime.config.ConfigServer;
013    
014    
015    public class MemoryControler {
016            private final static Map<String,MemoryType> types=new HashMap<String, MemoryType>();
017            private static boolean init;
018            public synchronized static void init(ConfigServer cs){
019                  if(init) return;
020                            // set level
021                  for (MemoryPoolMXBean pool : ManagementFactory.getMemoryPoolMXBeans()) {
022                      types.put(pool.getName(), pool.getType());
023                    // I don't know whether this approach is better, or whether
024                    // we should rather check for the pool name "Tenured Gen"?
025                      if (pool.getType() == MemoryType.HEAP && pool.isUsageThresholdSupported()) {
026                              long maxMemory = pool.getUsage().getMax();
027                              long warningThreshold = (long) (maxMemory * 0.9);
028                              //long warningThreshold = maxMemory -(10*1024*1024);
029                              pool.setUsageThreshold(warningThreshold);
030                      }
031                  }
032                  
033                  MemoryMXBean mbean = ManagementFactory.getMemoryMXBean();
034                  NotificationEmitter emitter = (NotificationEmitter) mbean;
035                  MemoryNotificationListener listener = new MemoryNotificationListener(types);
036                  emitter.addNotificationListener(listener, null, cs);
037                  init=true;
038            }
039    }