001/**
002 * Copyright 2005-2016 The Kuali Foundation
003 *
004 * Licensed under the Educational Community License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.opensource.org/licenses/ecl2.php
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016package org.kuali.rice.krad.devtools.util;
017
018import java.lang.management.ManagementFactory;
019import java.lang.management.MemoryMXBean;
020import java.lang.management.MemoryNotificationInfo;
021import java.lang.management.MemoryPoolMXBean;
022import java.lang.management.MemoryType;
023import java.util.ArrayList;
024import java.util.Collection;
025
026import javax.management.Notification;
027import javax.management.NotificationEmitter;
028import javax.management.NotificationListener;
029
030import org.apache.log4j.Logger;
031
032public class MemoryMonitor {
033    private final Collection<Listener> listeners = new ArrayList<Listener>();
034    private static final Logger LOG = Logger.getLogger(MemoryMonitor.class);
035    private String springContextId;
036
037    public interface Listener {
038        public void memoryUsageLow(String springContextId, long usedMemory, long maxMemory);
039    }
040
041    public MemoryMonitor() {
042        LOG.info("initializing");
043        this.springContextId = "Unknown";
044        MemoryMXBean mbean = ManagementFactory.getMemoryMXBean();
045        NotificationEmitter emitter = (NotificationEmitter) mbean;
046        emitter.addNotificationListener(new NotificationListener() {
047            public void handleNotification(Notification n, Object hb) {
048                if (n.getType().equals(MemoryNotificationInfo.MEMORY_THRESHOLD_EXCEEDED)) {
049                    long maxMemory = tenuredGenPool.getUsage().getMax();
050                    long usedMemory = tenuredGenPool.getUsage().getUsed();
051                    for (Listener listener : listeners) {
052                        listener.memoryUsageLow(springContextId, usedMemory, maxMemory);
053                    }
054                }
055            }
056        }, null, null);
057    }
058
059    public MemoryMonitor(String springContextId) {
060        this();
061        this.springContextId = springContextId;
062    }
063
064    public boolean addListener(Listener listener) {
065        return listeners.add(listener);
066    }
067
068    public boolean removeListener(Listener listener) {
069        return listeners.remove(listener);
070    }
071
072    private static final MemoryPoolMXBean tenuredGenPool = findTenuredGenPool();
073
074    public static void setPercentageUsageThreshold(double percentage) {
075        if (percentage <= 0.0 || percentage > 1.0) {
076            throw new IllegalArgumentException("percentage not in range");
077        }
078        long maxMemory = tenuredGenPool.getUsage().getMax();
079        long warningThreshold = (long) (maxMemory * percentage);
080        tenuredGenPool.setUsageThreshold(warningThreshold);
081    }
082
083    private static MemoryPoolMXBean findTenuredGenPool() {
084        for (MemoryPoolMXBean pool : ManagementFactory.getMemoryPoolMXBeans()) {
085            if (pool.getType() == MemoryType.HEAP && pool.isUsageThresholdSupported()) {
086                return pool;
087            }
088        }
089        throw new AssertionError("could not find tenured space");
090    }
091}