下面列出了javax.management.NotificationEmitter#addNotificationListener ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* emitters are used to listen to each memory pool (usually young / old gen). This function sets up the emitters
* if not already
*/
private synchronized void setupEmitters() {
if(emitters == null) {
emitters = new ArrayList<>();
// garbage collector for old and young gen
List<GarbageCollectorMXBean> garbageCollectorBeans = java.lang.management.ManagementFactory.getGarbageCollectorMXBeans();
logger.finest("Setting up listeners for garbage collection ");
for (GarbageCollectorMXBean garbageCollectorBean : garbageCollectorBeans) {
// to log
// listen to notification from the emitter
NotificationEmitter emitter = (NotificationEmitter) garbageCollectorBean;
emitters.add(emitter);
emitter.addNotificationListener(listener, null, null);
}
}
}
private void registerForNotifications() {
// Register the listener with MemoryMXBean
NotificationEmitter emitter = (NotificationEmitter) ManagementFactory.getMemoryMXBean();
emitter.addNotificationListener(listener, null, null);
// set collection usage threshold.
for (MemoryPoolMXBean pool : ManagementFactory.getMemoryPoolMXBeans()) {
if (pool.getType() == MemoryType.HEAP &&
pool.isUsageThresholdSupported() &&
pool.isCollectionUsageThresholdSupported()) {
long threshold = (pool.getUsage().getMax() * thresholdPercentage) / 100;
logger.info("setting collection threshold for " + pool.getName() +
" with max " + pool.getUsage().getMax() +
" to " + threshold);
pool.setCollectionUsageThreshold(threshold);
monitoredPools.put(pool.getName(), pool.getCollectionUsageThresholdCount());
} else {
logger.info("skip monitoring for pool " + pool.getName());
}
}
}
/**
* add listener to gc Garbage collector gc event
**/
@Override
public void addGCEventListener(NotificationListener listener){
List<GarbageCollectorMXBean> gcbeans = ManagementFactory.getGarbageCollectorMXBeans();
for (GarbageCollectorMXBean gcbean : gcbeans) {
NotificationEmitter emitter = (NotificationEmitter) gcbean;
emitter.addNotificationListener(listener, null, null);
}
}
public GarbageCollectionMonitor() {
List<GarbageCollectorMXBean> beans = ManagementFactory.getGarbageCollectorMXBeans();
for (GarbageCollectorMXBean bean : beans) {
if (!(bean instanceof NotificationEmitter)) {
continue;
}
NotificationEmitter notificationEmitter = (NotificationEmitter) bean;
notificationEmitter.addNotificationListener(this, null, null);
this.emitters.add(notificationEmitter);
}
}
private void monitor() {
double maxOldGen = JvmMemory.getOldGen().map(mem -> JvmMemory.getUsageValue(mem, MemoryUsage::getMax)).orElse(0.0);
for (GarbageCollectorMXBean mbean : ManagementFactory.getGarbageCollectorMXBeans()) {
if (!(mbean instanceof NotificationEmitter)) {
continue;
}
NotificationListener notificationListener = (notification, ref) -> {
if (!notification.getType().equals(GarbageCollectionNotificationInfo.GARBAGE_COLLECTION_NOTIFICATION)) {
return;
}
CompositeData cd = (CompositeData) notification.getUserData();
GarbageCollectionNotificationInfo notificationInfo = GarbageCollectionNotificationInfo.from(cd);
String gcCause = notificationInfo.getGcCause();
GcInfo gcInfo = notificationInfo.getGcInfo();
long duration = gcInfo.getDuration();
if (!JvmMemory.isConcurrentPhase(gcCause)) {
gcPauseSum.record(duration);
}
Map<String, MemoryUsage> after = gcInfo.getMemoryUsageAfterGc();
if (oldGenPoolName != null) {
final long oldAfter = after.get(oldGenPoolName).getUsed();
lastOldGenUsageAfterGc.set(oldAfter / maxOldGen);
}
};
NotificationEmitter notificationEmitter = (NotificationEmitter) mbean;
notificationEmitter.addNotificationListener(notificationListener, null, null);
notificationListenerCleanUpRunnables.add(() -> {
try {
notificationEmitter.removeNotificationListener(notificationListener);
} catch (ListenerNotFoundException ignore) {
}
});
}
}
/** monitor GC, and should the heap grow above 80% usage, clear some strong references */
protected void installGCMonitoring() {
List<GarbageCollectorMXBean> gcbeans = java.lang.management.ManagementFactory.getGarbageCollectorMXBeans();
for (GarbageCollectorMXBean gcbean : gcbeans) {
NotificationListener listener = createNotificationListener();
NotificationEmitter emitter = (NotificationEmitter) gcbean;
emitter.addNotificationListener(listener, null, null);
gcNotificationListeners.put(emitter, listener);
}
int heapUsageThresholdPercent = (int) Math.floor(heapUsageThreshold * 100f);
logger.info("installed GC monitors. will clear references if heap (after GC) is larger than " + heapUsageThresholdPercent + "%");
}
/** monitor GC, and should the heap grow above 80% usage, clear some strong references */
protected void installGCMonitoring() {
System.out.println("ReferenceManager.installGCMonitoring");
Set<String> ignoredMemoryAreas = new HashSet<>(Arrays.asList("Code Cache", "Compressed Class Space", "Metaspace"));
List<GarbageCollectorMXBean> gcbeans = java.lang.management.ManagementFactory.getGarbageCollectorMXBeans();
for (GarbageCollectorMXBean gcbean : gcbeans) {
NotificationListener listener = (notification, handback) -> {
if (notification.getType().equals(GarbageCollectionNotificationInfo.GARBAGE_COLLECTION_NOTIFICATION)) {
GarbageCollectionNotificationInfo info = GarbageCollectionNotificationInfo.from((CompositeData) notification.getUserData());
//sum up used and max memory across relevant memory areas
long totalMemUsed = 0;
long totalMemMax = 0;
for (Map.Entry<String, MemoryUsage> entry : info.getGcInfo().getMemoryUsageAfterGc().entrySet()) {
String name = entry.getKey();
if (!ignoredMemoryAreas.contains(name)) {
MemoryUsage detail = entry.getValue();
totalMemUsed += detail.getUsed();
totalMemMax += detail.getMax();
}
}
float heapUsageBefore = (float) totalMemUsed / (float) totalMemMax;
if (heapUsageBefore > 0.8) { //TODO make configurable
System.out.println("heap usage (after GC) is " + heapUsageBefore + ", clearing some references");
clearReferences();
}
}
};
NotificationEmitter emitter = (NotificationEmitter) gcbean;
emitter.addNotificationListener(listener, null, null);
}
}
/**
* Register with the JVM to get threshold events.
*
* Package private for testing.
*/
void startJVMThresholdListener() {
final MemoryPoolMXBean memoryPoolMXBean = getTenuredMemoryPoolMXBean();
// Set collection threshold to a low value, so that we can get
// notifications after every GC run. After each such collection
// threshold notification we set the usage thresholds to an
// appropriate value.
if (!testDisableMemoryUpdates) {
memoryPoolMXBean.setCollectionUsageThreshold(1);
// also set for notifications from survivor space GC
final MemoryPoolMXBean survivorPoolMXBean = getSurvivorPoolMXBean();
if (survivorPoolMXBean != null
&& survivorPoolMXBean.isCollectionUsageThresholdSupported()) {
survivorPoolMXBean.setCollectionUsageThreshold(1);
}
}
final long usageThreshold = memoryPoolMXBean.getUsageThreshold();
this.cache.getLoggerI18n().info(
LocalizedStrings.HeapMemoryMonitor_OVERRIDDING_MEMORYPOOLMXBEAN_HEAP_0_NAME_1,
new Object[] { Long.valueOf(usageThreshold), memoryPoolMXBean.getName() });
MemoryMXBean mbean = ManagementFactory.getMemoryMXBean();
NotificationEmitter emitter = (NotificationEmitter) mbean;
emitter.addNotificationListener(this, null, null);
}
/**
* Instantiate a JVM MIB intrusmentation.
* A <CODE>NotificationListener</CODE> is added to the <CODE>MemoryMXBean</CODE>
* <CODE>NotificationEmitter</CODE>
*/
public JVM_MANAGEMENT_MIB_IMPL() {
handler = new NotificationHandler();
emitter = (NotificationEmitter) ManagementFactory.getMemoryMXBean();
emitter.addNotificationListener(handler, null, null);
}
/**
* Instantiate a JVM MIB intrusmentation.
* A <CODE>NotificationListener</CODE> is added to the <CODE>MemoryMXBean</CODE>
* <CODE>NotificationEmitter</CODE>
*/
public JVM_MANAGEMENT_MIB_IMPL() {
handler = new NotificationHandler();
emitter = (NotificationEmitter) ManagementFactory.getMemoryMXBean();
emitter.addNotificationListener(handler, null, null);
}
public void subscribe(BiConsumer<Long, ?> printer) {
for (GarbageCollectorMXBean bean : ManagementFactory.getGarbageCollectorMXBeans()) {
NotificationEmitter emitter = (NotificationEmitter) bean;
emitter.addNotificationListener(listener, null, printer);
}
}
/**
* Instantiate a JVM MIB intrusmentation.
* A <CODE>NotificationListener</CODE> is added to the <CODE>MemoryMXBean</CODE>
* <CODE>NotificationEmitter</CODE>
*/
public JVM_MANAGEMENT_MIB_IMPL() {
handler = new NotificationHandler();
emitter = (NotificationEmitter) ManagementFactory.getMemoryMXBean();
emitter.addNotificationListener(handler, null, null);
}
public void installMonitor(){
//get all the GarbageCollectorMXBeans - there's one for each heap generation
//so probably two - the old generation and young generation
List<GarbageCollectorMXBean> gcbeans = java.lang.management.ManagementFactory.getGarbageCollectorMXBeans();
//Install a notification handler for each bean
for (GarbageCollectorMXBean gcbean : gcbeans) {
NotificationEmitter emitter = (NotificationEmitter) gcbean;
//use an anonymously generated listener for this example
// - proper code should really use a named class
NotificationListener listener = new NotificationListener() {
//keep a count of the total time spent in GCs
long totalGcDuration = 0;
//implement the notifier callback handler
@Override
public void handleNotification(Notification notification, Object handback) {
//we only handle GARBAGE_COLLECTION_NOTIFICATION notifications here
if (notification.getType().equals(GarbageCollectionNotificationInfo.GARBAGE_COLLECTION_NOTIFICATION)) {
//get the information associated with this notification
GarbageCollectionNotificationInfo info = GarbageCollectionNotificationInfo.from((CompositeData) notification.getUserData());
//get all the info and pretty print it
//Get the information about each memory space, and pretty print it
Map<String, MemoryUsage> membefore = info.getGcInfo().getMemoryUsageBeforeGc();
Map<String, MemoryUsage> mem = info.getGcInfo().getMemoryUsageAfterGc();
long memInit=0;
long memCommitted=0;
long memMax=0;
long memUsed=0;
// MemoryUsage before;
for (Map.Entry<String, MemoryUsage> entry : mem.entrySet()) {
String name = entry.getKey();
MemoryUsage memdetail = entry.getValue();
memInit += memdetail.getInit();
memCommitted += memdetail.getCommitted();
memMax += memdetail.getMax();
memUsed += memdetail.getUsed();
// MemoryUsage before = membefore.get(name);
// System.out.print(name + (memCommitted==memMax?"(fully expanded)":"(still expandable)") +"used: "+(beforepercent/10)+"."+(beforepercent%10)+"%->"+(percent/10)+"."+(percent%10)+"%("+((memUsed/1048576)+1)+"MB) / ");
}
// System.out.println(" Mem max (max used or available?)"+memMax/100000+" mem used (before or after?)"+memUsed/100000+" mem committed? ="+memCommitted/1000000);
if(memMax>maxMemMax)
maxMemMax=memMax;
if(memUsed>maxMemUsed)
maxMemUsed=memUsed;
if(memCommitted>maxMemCommitted)
maxMemCommitted= memCommitted;
}
}
};
//Add the listener
emitter.addNotificationListener(listener, null, null);
}
}
/**
* Instantiate a JVM MIB intrusmentation.
* A <CODE>NotificationListener</CODE> is added to the <CODE>MemoryMXBean</CODE>
* <CODE>NotificationEmitter</CODE>
*/
public JVM_MANAGEMENT_MIB_IMPL() {
handler = new NotificationHandler();
emitter = (NotificationEmitter) ManagementFactory.getMemoryMXBean();
emitter.addNotificationListener(handler, null, null);
}
/**
* Instantiate a JVM MIB intrusmentation.
* A <CODE>NotificationListener</CODE> is added to the <CODE>MemoryMXBean</CODE>
* <CODE>NotificationEmitter</CODE>
*/
public JVM_MANAGEMENT_MIB_IMPL() {
handler = new NotificationHandler();
emitter = (NotificationEmitter) ManagementFactory.getMemoryMXBean();
emitter.addNotificationListener(handler, null, null);
}
/**
* Instantiate a JVM MIB intrusmentation.
* A <CODE>NotificationListener</CODE> is added to the <CODE>MemoryMXBean</CODE>
* <CODE>NotificationEmitter</CODE>
*/
public JVM_MANAGEMENT_MIB_IMPL() {
handler = new NotificationHandler();
emitter = (NotificationEmitter) ManagementFactory.getMemoryMXBean();
emitter.addNotificationListener(handler, null, null);
}
/**
* Instantiate a JVM MIB intrusmentation.
* A <CODE>NotificationListener</CODE> is added to the <CODE>MemoryMXBean</CODE>
* <CODE>NotificationEmitter</CODE>
*/
public JVM_MANAGEMENT_MIB_IMPL() {
handler = new NotificationHandler();
emitter = (NotificationEmitter) ManagementFactory.getMemoryMXBean();
emitter.addNotificationListener(handler, null, null);
}
/**
* Instantiate a JVM MIB intrusmentation.
* A <CODE>NotificationListener</CODE> is added to the <CODE>MemoryMXBean</CODE>
* <CODE>NotificationEmitter</CODE>
*/
public JVM_MANAGEMENT_MIB_IMPL() {
handler = new NotificationHandler();
emitter = (NotificationEmitter) ManagementFactory.getMemoryMXBean();
emitter.addNotificationListener(handler, null, null);
}
/**
* Instantiate a JVM MIB intrusmentation.
* A <CODE>NotificationListener</CODE> is added to the <CODE>MemoryMXBean</CODE>
* <CODE>NotificationEmitter</CODE>
*/
public JVM_MANAGEMENT_MIB_IMPL() {
handler = new NotificationHandler();
emitter = (NotificationEmitter) ManagementFactory.getMemoryMXBean();
emitter.addNotificationListener(handler, null, null);
}
/**
* Instantiate a JVM MIB intrusmentation.
* A <CODE>NotificationListener</CODE> is added to the <CODE>MemoryMXBean</CODE>
* <CODE>NotificationEmitter</CODE>
*/
public JVM_MANAGEMENT_MIB_IMPL() {
handler = new NotificationHandler();
emitter = (NotificationEmitter) ManagementFactory.getMemoryMXBean();
emitter.addNotificationListener(handler, null, null);
}