Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
 package net.sf.kerner.utils.monitor.memory;
 
TODO Description

Author(s):
Heinz
Alexander Kerner
Version:
2011-09-19
public class LowMemoryNotifier {
    public static interface Listener {
        public void notice(long usedMemorylong maxMemory);
    }
    private static final MemoryPoolMXBean tenuredGenPool = findTenuredGenPool();
    private final static LowMemoryNotifier instance = new LowMemoryNotifier();
    private final Collection<Listenerlisteners = new ArrayList<Listener>();
    private LowMemoryNotifier() {
        final MemoryMXBean mbean = ManagementFactory.getMemoryMXBean();
        final NotificationEmitter emitter = (NotificationEmittermbean;
        emitter.addNotificationListener(new NotificationListener() {
            public void handleNotification(Notification nObject hb) {
                if (n.getType().equals(.)) {
                    long maxMemory = .getUsage().getMax();
                    long usedMemory = .getUsage().getUsed();
                    for (Listener listener : ) {
                        listener.notice(usedMemorymaxMemory);
                    }
                }
            }
        }, nullnull);
    }
    public synchronized boolean addListener(Listener listener) {
        return .add(listener);
    }
    public synchronized boolean removeListener(Listener listener) {
        return .remove(listener);
    }
    public static LowMemoryNotifier getInstance() {
        return ;
    }
    public static void setPercentageUsageThreshold(double percentage) {
        if (percentage <= 0.0 || percentage > 1.0) {
            throw new IllegalArgumentException("Percentage not in range");
        }
        long maxMemory = .getUsage().getMax();
        long warningThreshold = (long) (maxMemory * percentage);
        .setUsageThreshold(warningThreshold);
    }

    
Tenured Space Pool can be determined by it being of type HEAP and by it being possible to set the usage threshold.
    private static MemoryPoolMXBean findTenuredGenPool() {
        for (MemoryPoolMXBean pool : ManagementFactory.getMemoryPoolMXBeans()) {
            // I don't know whether this approach is better, or whether
            // we should rather check for the pool name "Tenured Gen"?
            if (pool.getType() == . && pool.isUsageThresholdSupported()) {
                return pool;
            }
        }
        throw new AssertionError("Could not find tenured space");
    }
New to GrepCode? Check out our FAQ X