001: /*
002: * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
003: *
004: * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
005: *
006: * The contents of this file are subject to the terms of either the GNU
007: * General Public License Version 2 only ("GPL") or the Common
008: * Development and Distribution License("CDDL") (collectively, the
009: * "License"). You may not use this file except in compliance with the
010: * License. You can obtain a copy of the License at
011: * http://www.netbeans.org/cddl-gplv2.html
012: * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
013: * specific language governing permissions and limitations under the
014: * License. When distributing the software, include this License Header
015: * Notice in each file and include the License file at
016: * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
017: * particular file as subject to the "Classpath" exception as provided
018: * by Sun in the GPL Version 2 section of the License file that
019: * accompanied this code. If applicable, add the following below the
020: * License Header, with the fields enclosed by brackets [] replaced by
021: * your own identifying information:
022: * "Portions Copyrighted [year] [name of copyright owner]"
023: *
024: * Contributor(s):
025: *
026: * The Original Software is NetBeans. The Initial Developer of the Original
027: * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
028: * Microsystems, Inc. All Rights Reserved.
029: *
030: * If you wish your version of this file to be governed by only the CDDL
031: * or only the GPL Version 2, indicate your decision by adding
032: * "[Contributor] elects to include this software in this distribution
033: * under the [CDDL or GPL Version 2] license." If you do not indicate a
034: * single choice of license, a recipient has the option to distribute
035: * your version of this file under either the CDDL, the GPL Version 2 or
036: * to extend the choice of license to its licensees as provided above.
037: * However, if you add GPL Version 2 code and therefore, elected the GPL
038: * Version 2 license, then the option applies only if the new code is
039: * made subject to such option by the copyright holder.
040: */
041:
042: package org.netbeans.modules.java.source.util;
043:
044: import java.lang.management.ManagementFactory;
045: import java.lang.management.MemoryMXBean;
046: import java.lang.management.MemoryNotificationInfo;
047: import java.lang.management.MemoryPoolMXBean;
048: import java.lang.management.MemoryType;
049: import java.lang.management.MemoryUsage;
050: import java.util.ArrayList;
051: import java.util.List;
052: import javax.management.ListenerNotFoundException;
053: import javax.management.Notification;
054: import javax.management.NotificationEmitter;
055: import javax.management.NotificationListener;
056: import org.openide.ErrorManager;
057:
058: /**
059: *
060: * @author Tomas Zezula
061: */
062: public class LowMemoryNotifier {
063:
064: private static final float DEFAULT_HEAP_LIMIT = 0.9f;
065:
066: private static LowMemoryNotifier instance;
067:
068: private final NotificationListener notificationListener = new Listener();
069: private final List<LowMemoryListener> listeners;
070: private MemoryPoolMXBean pool;
071: private MemoryPoolMXBean cachedPool; //Only initJMX may use this field!
072: private float heapLimit;
073:
074: /** Creates a new instance of LowMemoryNotifier */
075: private LowMemoryNotifier() {
076: this .heapLimit = DEFAULT_HEAP_LIMIT;
077: this .listeners = new ArrayList<LowMemoryListener>();
078: }
079:
080: float getHeapLimit() {
081: return this .heapLimit;
082: }
083:
084: void setHeapLimit(float heapLimit) {
085: this .heapLimit = heapLimit;
086: synchronized (this ) {
087: if (this .pool != null) {
088: MemoryUsage mu = pool.getUsage();
089: this .pool
090: .setUsageThreshold((long) (mu.getMax() * heapLimit));
091: }
092: }
093: }
094:
095: public synchronized void addLowMemoryListener(
096: final LowMemoryListener listener) {
097: assert listener != null;
098: if (this .pool == null) {
099: this .pool = initJMX();
100: }
101: assert this .pool != null;
102: final MemoryUsage usage = this .pool.getUsage();
103: assert usage != null : String.format(
104: "Pool %s returned null MemoryUsage, Valid: %s\n",
105: this .pool.getName(), this .pool.isValid() ? Boolean.TRUE
106: : Boolean.FALSE);
107: if (usage != null
108: && usage.getUsed() >= this .pool.getUsageThreshold()) {
109: listener.lowMemory(new LowMemoryEvent(this , this .pool));
110: }
111: this .listeners.add(listener);
112: }
113:
114: public synchronized void removeLowMemoryListener(
115: final LowMemoryListener listener) {
116: assert listener != null;
117: this .listeners.remove(listener);
118: if (this .listeners.isEmpty() && this .pool != null) {
119: finishJMX(this .pool);
120: this .pool = null;
121: }
122: }
123:
124: private void fireLowMemory() {
125: LowMemoryListener[] _listeners;
126: MemoryPoolMXBean _pool;
127: synchronized (this ) {
128: _listeners = this .listeners
129: .toArray(new LowMemoryListener[this .listeners
130: .size()]);
131: _pool = this .pool;
132: }
133: if (_listeners.length > 0) {
134: assert _pool != null;
135: final LowMemoryEvent event = new LowMemoryEvent(this , _pool);
136: for (LowMemoryListener l : _listeners) {
137: l.lowMemory(event);
138: }
139: }
140: }
141:
142: private MemoryPoolMXBean initJMX() {
143: List<MemoryPoolMXBean> pools = null;
144: if (this .cachedPool == null || !this .cachedPool.isValid()) {
145: pools = ManagementFactory.getMemoryPoolMXBeans();
146: for (MemoryPoolMXBean pool : pools) {
147: if (pool.getType() == MemoryType.HEAP
148: && pool.isUsageThresholdSupported()) { //NOI18N
149: this .cachedPool = pool;
150: break;
151: }
152: }
153: }
154: assert this .cachedPool != null : dumpMemoryPoolMXBean(pools);
155: if (this .cachedPool != null) {
156: MemoryUsage mu = this .cachedPool.getUsage();
157: this .cachedPool
158: .setUsageThreshold((long) (mu.getMax() * heapLimit));
159: MemoryMXBean mbean = ManagementFactory.getMemoryMXBean();
160: ((NotificationEmitter) mbean).addNotificationListener(
161: this .notificationListener, null, null);
162: }
163: return this .cachedPool;
164: }
165:
166: private void finishJMX(final MemoryPoolMXBean pool) {
167: assert pool != null;
168: try {
169: MemoryMXBean mbean = ManagementFactory.getMemoryMXBean();
170: ((NotificationEmitter) mbean)
171: .removeNotificationListener(this .notificationListener);
172: } catch (ListenerNotFoundException e) {
173: ErrorManager.getDefault().notify(e);
174: }
175: pool.setUsageThreshold(0);
176: }
177:
178: private class Listener implements NotificationListener {
179: public void handleNotification(Notification notification,
180: Object handback) {
181: final String notificationType = notification.getType();
182: if (notificationType
183: .equals(MemoryNotificationInfo.MEMORY_THRESHOLD_EXCEEDED)) {
184: fireLowMemory();
185: }
186: }
187:
188: }
189:
190: private static String dumpMemoryPoolMXBean(
191: List<MemoryPoolMXBean> pools) {
192: StringBuilder sb = new StringBuilder();
193: for (MemoryPoolMXBean pool : pools) {
194: sb.append(String.format(
195: "Pool: %s Type: %s TresholdSupported: %s\n", pool
196: .getName(), pool.getType(), pool
197: .isUsageThresholdSupported() ? Boolean.TRUE
198: : Boolean.FALSE));
199: }
200: sb.append('\n');
201: return sb.toString();
202: }
203:
204: public static synchronized LowMemoryNotifier getDefault() {
205: if (instance == null) {
206: instance = new LowMemoryNotifier();
207: }
208: return instance;
209: }
210:
211: }
|