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.gsfret.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: * This file is originally from Retouche, the Java Support
060: * infrastructure in NetBeans. I have modified the file as little
061: * as possible to make merging Retouche fixes back as simple as
062: * possible.
063: *
064: *
065: * @author tom
066: */
067: public class LowMemoryNotifier {
068:
069: private static final float DEFAULT_HEAP_LIMIT = 0.9f;
070:
071: private static LowMemoryNotifier instance;
072:
073: private final NotificationListener notificationListener = new Listener();
074: private final List<LowMemoryListener> listeners;
075: private MemoryPoolMXBean pool;
076: private MemoryPoolMXBean cachedPool; //Only initJMX may use this field!
077: private float heapLimit;
078:
079: /** Creates a new instance of LowMemoryNotifier */
080: private LowMemoryNotifier() {
081: this .heapLimit = DEFAULT_HEAP_LIMIT;
082: this .listeners = new ArrayList<LowMemoryListener>();
083: }
084:
085: float getHeapLimit() {
086: return this .heapLimit;
087: }
088:
089: void setHeapLimit(float heapLimit) {
090: this .heapLimit = heapLimit;
091: synchronized (this ) {
092: if (this .pool != null) {
093: MemoryUsage mu = pool.getUsage();
094: this .pool
095: .setUsageThreshold((long) (mu.getMax() * heapLimit));
096: }
097: }
098: }
099:
100: public synchronized void addLowMemoryListener(
101: final LowMemoryListener listener) {
102: assert listener != null;
103: if (this .pool == null) {
104: this .pool = initJMX();
105: }
106: assert this .pool != null;
107: final MemoryUsage usage = this .pool.getUsage();
108: assert usage != null : String.format(
109: "Pool %s returned null MemoryUsage, Valid: %s\n",
110: this .pool.getName(), this .pool.isValid() ? Boolean.TRUE
111: : Boolean.FALSE);
112: if (usage != null
113: && usage.getUsed() >= this .pool.getUsageThreshold()) {
114: listener.lowMemory(new LowMemoryEvent(this , this .pool));
115: }
116: this .listeners.add(listener);
117: }
118:
119: public synchronized void removeLowMemoryListener(
120: final LowMemoryListener listener) {
121: assert listener != null;
122: this .listeners.remove(listener);
123: if (this .listeners.isEmpty() && this .pool != null) {
124: finishJMX(this .pool);
125: this .pool = null;
126: }
127: }
128:
129: private void fireLowMemory() {
130: LowMemoryListener[] _listeners;
131: MemoryPoolMXBean _pool;
132: synchronized (this ) {
133: _listeners = this .listeners
134: .toArray(new LowMemoryListener[this .listeners
135: .size()]);
136: _pool = this .pool;
137: }
138: if (_listeners.length > 0) {
139: assert _pool != null;
140: final LowMemoryEvent event = new LowMemoryEvent(this , _pool);
141: for (LowMemoryListener l : _listeners) {
142: l.lowMemory(event);
143: }
144: }
145: }
146:
147: private MemoryPoolMXBean initJMX() {
148: List<MemoryPoolMXBean> pools = null;
149: if (this .cachedPool == null || !this .cachedPool.isValid()) {
150: pools = ManagementFactory.getMemoryPoolMXBeans();
151: for (MemoryPoolMXBean pool : pools) {
152: if (pool.getType() == MemoryType.HEAP
153: && pool.isUsageThresholdSupported()) { //NOI18N
154: this .cachedPool = pool;
155: break;
156: }
157: }
158: }
159: assert this .cachedPool != null : dumpMemoryPoolMXBean(pools);
160: if (this .cachedPool != null) {
161: MemoryUsage mu = this .cachedPool.getUsage();
162: this .cachedPool
163: .setUsageThreshold((long) (mu.getMax() * heapLimit));
164: MemoryMXBean mbean = ManagementFactory.getMemoryMXBean();
165: ((NotificationEmitter) mbean).addNotificationListener(
166: this .notificationListener, null, null);
167: }
168: return this .cachedPool;
169: }
170:
171: private void finishJMX(final MemoryPoolMXBean pool) {
172: assert pool != null;
173: try {
174: MemoryMXBean mbean = ManagementFactory.getMemoryMXBean();
175: ((NotificationEmitter) mbean)
176: .removeNotificationListener(this .notificationListener);
177: } catch (ListenerNotFoundException e) {
178: ErrorManager.getDefault().notify(e);
179: }
180: pool.setUsageThreshold(0);
181: }
182:
183: private class Listener implements NotificationListener {
184: public void handleNotification(Notification notification,
185: Object handback) {
186: final String notificationType = notification.getType();
187: if (notificationType
188: .equals(MemoryNotificationInfo.MEMORY_THRESHOLD_EXCEEDED)) {
189: fireLowMemory();
190: }
191: }
192:
193: }
194:
195: private static String dumpMemoryPoolMXBean(
196: List<MemoryPoolMXBean> pools) {
197: StringBuilder sb = new StringBuilder();
198: for (MemoryPoolMXBean pool : pools) {
199: sb.append(String.format(
200: "Pool: %s Type: %s TresholdSupported: %s\n", pool
201: .getName(), pool.getType(), pool
202: .isUsageThresholdSupported() ? Boolean.TRUE
203: : Boolean.FALSE));
204: }
205: sb.append('\n');
206: return sb.toString();
207: }
208:
209: public static synchronized LowMemoryNotifier getDefault() {
210: if (instance == null) {
211: instance = new LowMemoryNotifier();
212: }
213: return instance;
214: }
215:
216: }
|