001/**
002 *
003 * Copyright (c) 2014, the Railo Company Ltd. All rights reserved.
004 *
005 * This library is free software; you can redistribute it and/or
006 * modify it under the terms of the GNU Lesser General Public
007 * License as published by the Free Software Foundation; either 
008 * version 2.1 of the License, or (at your option) any later version.
009 * 
010 * This library is distributed in the hope that it will be useful,
011 * but WITHOUT ANY WARRANTY; without even the implied warranty of
012 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
013 * Lesser General Public License for more details.
014 * 
015 * You should have received a copy of the GNU Lesser General Public 
016 * License along with this library.  If not, see <http://www.gnu.org/licenses/>.
017 * 
018 **/
019package lucee.commons.management;
020
021import java.lang.management.ManagementFactory;
022import java.lang.management.MemoryMXBean;
023import java.lang.management.MemoryPoolMXBean;
024import java.lang.management.MemoryType;
025import java.util.HashMap;
026import java.util.Map;
027
028import javax.management.NotificationEmitter;
029
030import lucee.runtime.config.ConfigServer;
031
032
033public class MemoryControler {
034        private final static Map<String,MemoryType> types=new HashMap<String, MemoryType>();
035        private static boolean init;
036        public synchronized static void init(ConfigServer cs){
037              if(init) return;
038                        // set level
039              for (MemoryPoolMXBean pool : ManagementFactory.getMemoryPoolMXBeans()) {
040                  types.put(pool.getName(), pool.getType());
041                // I don't know whether this approach is better, or whether
042                // we should rather check for the pool name "Tenured Gen"?
043                  if (pool.getType() == MemoryType.HEAP && pool.isUsageThresholdSupported()) {
044                          long maxMemory = pool.getUsage().getMax();
045                          long warningThreshold = (long) (maxMemory * 0.9);
046                          //long warningThreshold = maxMemory -(10*1024*1024);
047                          pool.setUsageThreshold(warningThreshold);
048                  }
049              }
050              
051              MemoryMXBean mbean = ManagementFactory.getMemoryMXBean();
052              NotificationEmitter emitter = (NotificationEmitter) mbean;
053              MemoryNotificationListener listener = new MemoryNotificationListener(types);
054              emitter.addNotificationListener(listener, null, cs);
055              init=true;
056        }
057}