001/**
002 * Copyright 2005-2015 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.logging.log4j.Logger;
031import org.apache.logging.log4j.LogManager;
032
033public class MemoryMonitor {
034    private final Collection<Listener> listeners = new ArrayList<Listener>();
035    private static final Logger LOG = LogManager.getLogger(MemoryMonitor.class);
036    private String springContextId;
037
038    public interface Listener {
039        public void memoryUsageLow(String springContextId, long usedMemory, long maxMemory);
040    }
041
042    public MemoryMonitor() {
043        LOG.info("initializing");
044        this.springContextId = "Unknown";
045        MemoryMXBean mbean = ManagementFactory.getMemoryMXBean();
046        NotificationEmitter emitter = (NotificationEmitter) mbean;
047        emitter.addNotificationListener(new NotificationListener() {
048            public void handleNotification(Notification n, Object hb) {
049                if (n.getType().equals(MemoryNotificationInfo.MEMORY_THRESHOLD_EXCEEDED)) {
050                    long maxMemory = tenuredGenPool.getUsage().getMax();
051                    long usedMemory = tenuredGenPool.getUsage().getUsed();
052                    for (Listener listener : listeners) {
053                        listener.memoryUsageLow(springContextId, usedMemory, maxMemory);
054                    }
055                }
056            }
057        }, null, null);
058    }
059
060    public MemoryMonitor(String springContextId) {
061        this();
062        this.springContextId = springContextId;
063    }
064
065    public boolean addListener(Listener listener) {
066        return listeners.add(listener);
067    }
068
069    public boolean removeListener(Listener listener) {
070        return listeners.remove(listener);
071    }
072
073    private static final MemoryPoolMXBean tenuredGenPool = findTenuredGenPool();
074
075    public static void setPercentageUsageThreshold(double percentage) {
076        if (percentage <= 0.0 || percentage > 1.0) {
077            throw new IllegalArgumentException("percentage not in range");
078        }
079        long maxMemory = tenuredGenPool.getUsage().getMax();
080        long warningThreshold = (long) (maxMemory * percentage);
081        tenuredGenPool.setUsageThreshold(warningThreshold);
082    }
083
084    private static MemoryPoolMXBean findTenuredGenPool() {
085        for (MemoryPoolMXBean pool : ManagementFactory.getMemoryPoolMXBeans()) {
086            if (pool.getType() == MemoryType.HEAP && pool.isUsageThresholdSupported()) {
087                return pool;
088            }
089        }
090        throw new AssertionError("could not find tenured space");
091    }
092}