Java Code Examples for javax.management.NotificationEmitter.addNotificationListener()

The following are Jave code examples for showing how to use addNotificationListener() of the javax.management.NotificationEmitter class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: otus_java_2017_06   File: Main.java   View Source Code Vote up 6 votes
private static void installGCMonitoring() {
    List<GarbageCollectorMXBean> gcbeans = java.lang.management.ManagementFactory.getGarbageCollectorMXBeans();
    for (GarbageCollectorMXBean gcbean : gcbeans) {
        NotificationEmitter emitter = (NotificationEmitter) gcbean;
        System.out.println(gcbean.getName());

        NotificationListener listener = (notification, handback) -> {
            if (notification.getType().equals(GarbageCollectionNotificationInfo.GARBAGE_COLLECTION_NOTIFICATION)) {
                GarbageCollectionNotificationInfo info = GarbageCollectionNotificationInfo.from((CompositeData) notification.getUserData());

                long duration = info.getGcInfo().getDuration();
                String gctype = info.getGcAction();

                System.out.println(gctype + ": - "
                        + info.getGcInfo().getId() + ", "
                        + info.getGcName()
                        + " (from " + info.getGcCause() + ") " + duration + " milliseconds");

            }
        };

        emitter.addNotificationListener(listener, null, null);
    }
}
 
Example 2
Project: otus_java_2017_04   File: Main.java   View Source Code Vote up 6 votes
private static void installGCMonitoring() {
    List<GarbageCollectorMXBean> gcbeans = java.lang.management.ManagementFactory.getGarbageCollectorMXBeans();
    for (GarbageCollectorMXBean gcbean : gcbeans) {
        NotificationEmitter emitter = (NotificationEmitter) gcbean;
        System.out.println(gcbean.getName());

        NotificationListener listener = (notification, handback) -> {
            if (notification.getType().equals(GarbageCollectionNotificationInfo.GARBAGE_COLLECTION_NOTIFICATION)) {
                GarbageCollectionNotificationInfo info = GarbageCollectionNotificationInfo.from((CompositeData) notification.getUserData());

                long duration = info.getGcInfo().getDuration();
                String gctype = info.getGcAction();

                System.out.println(gctype + ": - "
                        + info.getGcInfo().getId() + ", "
                        + info.getGcName()
                        + " (from " + info.getGcCause() + ") " + duration + " milliseconds");

            }
        };

        emitter.addNotificationListener(listener, null, null);
    }
}
 
Example 3
Project: monarch   File: HeapMemoryMonitor.java   View Source Code Vote up 6 votes
/**
 * 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);
  }

  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);
}
 
Example 4
Project: kc-rice   File: MemoryMonitor.java   View Source Code Vote up 6 votes
public MemoryMonitor() {
    LOG.info("initializing");
    this.springContextId = "Unknown";
    MemoryMXBean mbean = ManagementFactory.getMemoryMXBean();
    NotificationEmitter emitter = (NotificationEmitter) mbean;
    emitter.addNotificationListener(new NotificationListener() {
        public void handleNotification(Notification n, Object hb) {
            if (n.getType().equals(MemoryNotificationInfo.MEMORY_THRESHOLD_EXCEEDED)) {
                long maxMemory = tenuredGenPool.getUsage().getMax();
                long usedMemory = tenuredGenPool.getUsage().getUsed();
                for (Listener listener : listeners) {
                    listener.memoryUsageLow(springContextId, usedMemory, maxMemory);
                }
            }
        }
    }, null, null);
}
 
Example 5
Project: SOMns   File: ActorExecutionTrace.java   View Source Code Vote up 6 votes
public static void setUpGCMonitoring() {
  for (java.lang.management.GarbageCollectorMXBean bean : gcbeans) {
    NotificationEmitter emitter = (NotificationEmitter) bean;
    NotificationListener listener = new NotificationListener() {
      @Override
      public void handleNotification(final Notification notification,
          final Object handback) {
        if (GarbageCollectionNotificationInfo.GARBAGE_COLLECTION_NOTIFICATION.equals(
            notification.getType())) {
          GarbageCollectionNotificationInfo info = GarbageCollectionNotificationInfo.from(
              (CompositeData) notification.getUserData());
          long after = getTotal(info.getGcInfo().getMemoryUsageAfterGc());
          long before = getTotal(info.getGcInfo().getMemoryUsageBeforeGc());
          collectedMemory += before - after;
        }
      }
    };
    emitter.addNotificationListener(listener, null, null);
  }
}
 
Example 6
Project: Lucee4   File: MemoryControler.java   View Source Code Vote up 6 votes
public synchronized static void init(ConfigServer cs){
      if(init) return;
		// set level
      for (MemoryPoolMXBean pool : ManagementFactory.getMemoryPoolMXBeans()) {
    	  types.put(pool.getName(), pool.getType());
        // I don't know whether this approach is better, or whether
        // we should rather check for the pool name "Tenured Gen"?
    	  if (pool.getType() == MemoryType.HEAP && pool.isUsageThresholdSupported()) {
    		  long maxMemory = pool.getUsage().getMax();
    		  long warningThreshold = (long) (maxMemory * 0.9);
    		  //long warningThreshold = maxMemory -(10*1024*1024);
    		  pool.setUsageThreshold(warningThreshold);
    	  }
      }
      
      MemoryMXBean mbean = ManagementFactory.getMemoryMXBean();
      NotificationEmitter emitter = (NotificationEmitter) mbean;
      MemoryNotificationListener listener = new MemoryNotificationListener(types);
      emitter.addNotificationListener(listener, null, cs);
      init=true;
}
 
Example 7
Project: Lucee   File: MemoryControler.java   View Source Code Vote up 6 votes
public synchronized static void init(ConfigServer cs){
      if(init) return;
		// set level
      for (MemoryPoolMXBean pool : ManagementFactory.getMemoryPoolMXBeans()) {
    	  types.put(pool.getName(), pool.getType());
        // I don't know whether this approach is better, or whether
        // we should rather check for the pool name "Tenured Gen"?
    	  if (pool.getType() == MemoryType.HEAP && pool.isUsageThresholdSupported()) {
    		  long maxMemory = pool.getUsage().getMax();
    		  long warningThreshold = (long) (maxMemory * 0.9);
    		  //long warningThreshold = maxMemory -(10*1024*1024);
    		  pool.setUsageThreshold(warningThreshold);
    	  }
      }
      
      MemoryMXBean mbean = ManagementFactory.getMemoryMXBean();
      NotificationEmitter emitter = (NotificationEmitter) mbean;
      MemoryNotificationListener listener = new MemoryNotificationListener(types);
      emitter.addNotificationListener(listener, null, cs);
      init=true;
}
 
Example 8
Project: spectator   File: GcLogger.java   View Source Code Vote up 6 votes
/**
 * Start collecting data about GC events.
 *
 * @param listener
 *     If not null, the listener will be called with the event objects after metrics and the
 *     log buffer is updated.
 */
public synchronized void start(GcEventListener listener) {
  // TODO: this class has a bad mix of static fields used from an instance of the class. For now
  // this has been changed not to throw to make the dependency injection use-cases work. A
  // more general refactor of the GcLogger class is needed.
  if (notifListener != null) {
    LOGGER.warn("logger already started");
    return;
  }
  eventListener = listener;
  notifListener = new GcNotificationListener();
  for (GarbageCollectorMXBean mbean : ManagementFactory.getGarbageCollectorMXBeans()) {
    if (mbean instanceof NotificationEmitter) {
      final NotificationEmitter emitter = (NotificationEmitter) mbean;
      emitter.addNotificationListener(notifListener, null, null);
    }
  }
}
 
Example 9
Project: pitest   File: MemoryWatchdog.java   View Source Code Vote up 6 votes
public static void addWatchDogToAllPools(final long threshold,
    final NotificationListener listener) {
  final MemoryMXBean memBean = ManagementFactory.getMemoryMXBean();
  final NotificationEmitter ne = (NotificationEmitter) memBean;

  ne.addNotificationListener(listener, null, null);

  final List<MemoryPoolMXBean> memPools = ManagementFactory
      .getMemoryPoolMXBeans();
  for (final MemoryPoolMXBean mp : memPools) {
    if (mp.isUsageThresholdSupported()) {
      final MemoryUsage mu = mp.getUsage();
      final long max = mu.getMax();
      final long alert = (max * threshold) / 100;
      // LOG.info("Setting a threshold shutdown on pool: " + mp.getName()
      // + " for: " + alert);
      mp.setUsageThreshold(alert);

    }
  }
}
 
Example 10
Project: bazel   File: RetainedHeapLimiter.java   View Source Code Vote up 6 votes
void install() {
  Preconditions.checkState(!installed, "RetainedHeapLimiter installed twice");
  installed = true;
  List<GarbageCollectorMXBean> gcbeans = ManagementFactory.getGarbageCollectorMXBeans();
  boolean foundTenured = false;
  // Examine all collectors and register for notifications from those which collect the tenured
  // space. Normally there is one such collector.
  for (GarbageCollectorMXBean gcbean : gcbeans) {
    boolean collectsTenured = false;
    for (String name : gcbean.getMemoryPoolNames()) {
      collectsTenured |= isTenuredSpace(name);
    }
    if (collectsTenured) {
      foundTenured = true;
      NotificationEmitter emitter = (NotificationEmitter) gcbean;
      emitter.addNotificationListener(this, null, null);
    }
  }
  if (!foundTenured) {
    throw new IllegalStateException(
        "Can't find tenured space; update this class for a new collector");
  }
}
 
Example 11
Project: rice   File: MemoryMonitor.java   View Source Code Vote up 6 votes
public MemoryMonitor() {
    LOG.info("initializing");
    this.springContextId = "Unknown";
    MemoryMXBean mbean = ManagementFactory.getMemoryMXBean();
    NotificationEmitter emitter = (NotificationEmitter) mbean;
    emitter.addNotificationListener(new NotificationListener() {
        public void handleNotification(Notification n, Object hb) {
            if (n.getType().equals(MemoryNotificationInfo.MEMORY_THRESHOLD_EXCEEDED)) {
                long maxMemory = tenuredGenPool.getUsage().getMax();
                long usedMemory = tenuredGenPool.getUsage().getUsed();
                for (Listener listener : listeners) {
                    listener.memoryUsageLow(springContextId, usedMemory, maxMemory);
                }
            }
        }
    }, null, null);
}
 
Example 12
Project: scaleDOM   File: LowMemoryDetector.java   View Source Code Vote up 6 votes
/**
 * Default constructor.
 * 
 * @param memoryThresholdFactor amount of memory to be considered 'enough memory'.
 * @throws IllegalArgumentException If memoryThresholdFactor is not strictly between 0.0 and 1.0.
 */
public LowMemoryDetector(final double memoryThresholdFactor) {
	checkArgument(memoryThresholdFactor > 0.0 && memoryThresholdFactor < 1.0,
			"Expected memoryThresholdFactor to be between 0.0 and 1.0, %s is not.", memoryThresholdFactor);

	isLowMemory = false;

	// Find the tenured heap
	tenuredHeap = findTenuredHeap();
	checkNotNull(tenuredHeap, "Expected tenuredHeap to be not null.");
	tenuredHeapSize = tenuredHeap.getUsage().getMax();
	log.debug("Determined the tenured heap as '{}' (size: {} B).", tenuredHeap.getName(), tenuredHeapSize);

	// Monitor tenured heap
	memoryThreshold = (long) (tenuredHeapSize * memoryThresholdFactor);
	tenuredHeap.setCollectionUsageThreshold(memoryThreshold);
	log.debug("Low memory threshold is {} B.", memoryThreshold);

	// Add notification listener
	final NotificationEmitter notificationEmitter = (NotificationEmitter) ManagementFactory.getMemoryMXBean();
	notificationEmitter.addNotificationListener(this, null, null);
}
 
Example 13
Project: kuali_rice   File: MemoryMonitor.java   View Source Code Vote up 6 votes
public MemoryMonitor() {
    LOG.info("initializing");
    this.springContextId = "Unknown";
    MemoryMXBean mbean = ManagementFactory.getMemoryMXBean();
    NotificationEmitter emitter = (NotificationEmitter) mbean;
    emitter.addNotificationListener(new NotificationListener() {
        public void handleNotification(Notification n, Object hb) {
            if (n.getType().equals(MemoryNotificationInfo.MEMORY_THRESHOLD_EXCEEDED)) {
                long maxMemory = tenuredGenPool.getUsage().getMax();
                long usedMemory = tenuredGenPool.getUsage().getUsed();
                for (Listener listener : listeners) {
                    listener.memoryUsageLow(springContextId, usedMemory, maxMemory);
                }
            }
        }
    }, null, null);
}
 
Example 14
Project: consulo   File: PerformanceWatcher.java   View Source Code Vote up 6 votes
private void watchCodeCache(final MemoryPoolMXBean bean) {
  final long threshold = bean.getUsage().getMax() - 5 * 1024 * 1024;
  if (!bean.isUsageThresholdSupported() || threshold <= 0) return;

  bean.setUsageThreshold(threshold);
  final NotificationEmitter emitter = (NotificationEmitter)ManagementFactory.getMemoryMXBean();
  emitter.addNotificationListener(new NotificationListener() {
    @Override
    public void handleNotification(Notification n, Object hb) {
      if (bean.getUsage().getUsed() > threshold) {
        LOG.info("Code Cache is almost full");
        dumpThreads("codeCacheFull", true);
        try {
          emitter.removeNotificationListener(this);
        }
        catch (ListenerNotFoundException e) {
          LOG.error(e);
        }
      }
    }
  }, null, null);
}
 
Example 15
Project: aurora-prometheus   File: JvmGcMetrics.java   View Source Code Vote up 5 votes
public JvmGcMetrics() {
    histogram = Histogram.build().name("jvm_gc_hist").help("garbage collection metrics as a histogram")
        .labelNames(new String[] { KEY_NAME, KEY_CAUSE, KEY_ACTION }).create();

    for (GarbageCollectorMXBean gcbean : ManagementFactory.getGarbageCollectorMXBeans()) {
        final NotificationEmitter emitter = (NotificationEmitter) gcbean;
        emitter.addNotificationListener(gcListener, null, null);
    }
}
 
Example 16
Project: gemfirexd-oss   File: HeapMemoryMonitor.java   View Source Code Vote up 5 votes
/**
 * 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);
}
 
Example 17
Project: gc-monitor   File: GcMonitor.java   View Source Code Vote up 5 votes
public synchronized void start() {
    if (started) {
        // already started
        return;
    }
    started = true;

    for (GarbageCollectorMXBean bean : configuration.getGarbageCollectorMXBeans()) {
        NotificationEmitter emitter = (NotificationEmitter) bean;
        emitter.addNotificationListener(this, null, bean.getName());
    }
}
 
Example 18
Project: demidovii   File: Sorter.java   View Source Code Vote up 5 votes
public final void requestMemoryWarnings() {
  List<MemoryPoolMXBean> pools = ManagementFactory.getMemoryPoolMXBeans();
  long maxPoolSize = 0;
  MemoryPoolMXBean biggestPool = null;

  for (MemoryPoolMXBean pool : pools) {
    if (pool.getType() != MemoryType.HEAP) {
      continue;
    }
    MemoryUsage usage = pool.getUsage();

    if (pool.isUsageThresholdSupported()
            && usage.getMax() > maxPoolSize) {
      maxPoolSize = usage.getMax();
      biggestPool = pool;
    }
  }

  if (biggestPool != null) {
    biggestPool.setUsageThreshold((long) (maxPoolSize * this.memoryFraction));
    MemoryMXBean memoryBean = ManagementFactory.getMemoryMXBean();
    NotificationEmitter emitter = (NotificationEmitter) memoryBean;
    emitter.addNotificationListener(this, null, null);
  } else {
    throw new RuntimeException("Memory monitoring is not supported.");
  }
}
 
Example 19
Project: gemfirexd-oss   File: HeapMemoryMonitor.java   View Source Code Vote up 5 votes
/**
 * 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);
}
 
Example 20
Project: EchoX3   File: GarbageInfo.java   View Source Code Vote up 5 votes
private static GarbageInfo getGarbageInfo(
		GarbageCollectorMXBean bean, String[] poolNames, String poolContainText)
{
	String					primaryPoolName			= null;
	for (String poolName : poolNames)
	{
		if (poolName.contains(poolContainText))
		{
			primaryPoolName = poolName;
		}
	}
	if (null == primaryPoolName)
	{
		return null;
	}

	GarbageInfo				garbageInfo				= new GarbageInfo(bean, poolContainText);
	garbageInfo.m_primaryPoolName	= primaryPoolName;

	if (garbageInfo.getGarbageBean() instanceof NotificationEmitter)
	{
		NotificationEmitter				notificationEmitter	= (NotificationEmitter) garbageInfo.getGarbageBean();
		GarbageNotificationListener		listener			= new GarbageNotificationListener();
		notificationEmitter.addNotificationListener(listener, null, garbageInfo);
	}

	return garbageInfo;
}
 
Example 21
Project: galago-git   File: Sorter.java   View Source Code Vote up 5 votes
public final void requestMemoryWarnings() {
  List<MemoryPoolMXBean> pools = ManagementFactory.getMemoryPoolMXBeans();
  long maxPoolSize = 0;
  MemoryPoolMXBean biggestPool = null;

  for (MemoryPoolMXBean pool : pools) {
    if (pool.getType() != MemoryType.HEAP) {
      continue;
    }
    MemoryUsage usage = pool.getUsage();

    if (pool.isUsageThresholdSupported()
            && usage.getMax() > maxPoolSize) {
      maxPoolSize = usage.getMax();
      biggestPool = pool;
    }
  }

  if (biggestPool != null) {
    biggestPool.setUsageThreshold((long) (maxPoolSize * this.memoryFraction));
    MemoryMXBean memoryBean = ManagementFactory.getMemoryMXBean();
    NotificationEmitter emitter = (NotificationEmitter) memoryBean;
    emitter.addNotificationListener(this, null, null);
  } else {
    throw new RuntimeException("Memory monitoring is not supported.");
  }
}
 
Example 22
Project: galagosearch   File: Sorter.java   View Source Code Vote up 5 votes
public void requestMemoryWarnings() {
    List<MemoryPoolMXBean> pools = ManagementFactory.getMemoryPoolMXBeans();
    long maxPoolSize = 0;
    MemoryPoolMXBean biggestPool = null;

    for (MemoryPoolMXBean pool : pools) {
        if (pool.getType() != MemoryType.HEAP) {
            continue;
        }
        MemoryUsage usage = pool.getUsage();

        if (pool.isUsageThresholdSupported() &&
                usage.getMax() > maxPoolSize) {
            maxPoolSize = usage.getMax();
            biggestPool = pool;
        }
    }

    if (biggestPool != null) {
        biggestPool.setUsageThreshold((long) (maxPoolSize * 0.7));
        MemoryMXBean memoryBean = ManagementFactory.getMemoryMXBean();
        NotificationEmitter emitter = (NotificationEmitter) memoryBean;
        emitter.addNotificationListener(this, null, null);
    } else {
        throw new RuntimeException("Memory monitoring is not supported.");
    }
}
 
Example 23
Project: Rainfall-core   File: GcStatisticsCollector.java   View Source Code Vote up 5 votes
@Override
public void initialize() {
  List<GarbageCollectorMXBean> gcMxBeans = java.lang.management.ManagementFactory.getGarbageCollectorMXBeans();
  for (GarbageCollectorMXBean gcMxBean : gcMxBeans) {
    NotificationEmitter emitter = (NotificationEmitter)gcMxBean;
    emitter.addNotificationListener(listener, null, null);
  }
}
 
Example 24
Project: mondrian-3.1.5   File: NotificationMemoryMonitor.java   View Source Code Vote up 5 votes
/**
 * Construct a <code>NotificationMemoryMonitor</code> instance and
 * register it with the Java5 memory management system.
 */
NotificationMemoryMonitor() {
    super();
    final MemoryMXBean mbean = ManagementFactory.getMemoryMXBean();
    final NotificationEmitter emitter = (NotificationEmitter) mbean;

    // register with the Java5 memory management system.
    emitter.addNotificationListener(new NotificationHandler(), null, null);
}
 
Example 25
Project: GalagoGUI   File: Sorter.java   View Source Code Vote up 5 votes
public void requestMemoryWarnings() {
    List<MemoryPoolMXBean> pools = ManagementFactory.getMemoryPoolMXBeans();
    long maxPoolSize = 0;
    MemoryPoolMXBean biggestPool = null;

    for (MemoryPoolMXBean pool : pools) {
        if (pool.getType() != MemoryType.HEAP) {
            continue;
        }
        MemoryUsage usage = pool.getUsage();

        if (pool.isUsageThresholdSupported() &&
                usage.getMax() > maxPoolSize) {
            maxPoolSize = usage.getMax();
            biggestPool = pool;
        }
    }

    if (biggestPool != null) {
        biggestPool.setUsageThreshold((long) (maxPoolSize * 0.7));
        MemoryMXBean memoryBean = ManagementFactory.getMemoryMXBean();
        NotificationEmitter emitter = (NotificationEmitter) memoryBean;
        emitter.addNotificationListener(this, null, null);
    } else {
        throw new RuntimeException("Memory monitoring is not supported.");
    }
}
 
Example 26
Project: btrace   File: BTraceRuntime.java   View Source Code Vote up 5 votes
private void startImpl() {
    if (timerHandlers != null && timerHandlers.length != 0) {
        timer = new Timer(true);
        RunnableGenerator gen = getRunnableGenerator();
        Runnable[] runnables = new Runnable[timerHandlers.length];
        if (gen != null) {
            generateRunnables(gen, runnables);
        } else {
            wrapToRunnables(runnables);
        }
        for (int index = 0; index < timerHandlers.length; index++) {
            Method m = timerHandlers[index];
            OnTimer tp = m.getAnnotation(OnTimer.class);
            long period = tp.value();
            final Runnable r = runnables[index];
            timer.schedule(new TimerTask() {
                public void run() { r.run(); }
            }, period, period);
        }
    }

    if (! lowMemHandlers.isEmpty()) {
        initMemoryMBean();
        initMemoryListener();
        NotificationEmitter emitter = (NotificationEmitter) memoryMBean;
        emitter.addNotificationListener(memoryListener, null, null);
    }

    leave();
}
 
Example 27
Project: G2Dj   File: Debug.java   View Source Code Vote up 4 votes
public static void enableGarbageCollectionLogging()
{
    //get all the GarbageCollectorMXBeans - there's one for each heap generation
    //so probably two - the old generation and young generation
    List<java.lang.management.GarbageCollectorMXBean> gcbeans = java.lang.management.ManagementFactory.getGarbageCollectorMXBeans();
    //Install a notifcation handler for each bean
    for (GarbageCollectorMXBean gcbean : gcbeans) 
    {
        System.out.println(gcbean);
        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());
                    
                    String gctype = info.getGcAction();
                    if ("end of minor GC".equals(gctype))
                        gctype = "Young Gen GC";
                    else if ("end of major GC".equals(gctype))
                        gctype = "Old Gen GC";
                    
                    StringBuilder sb = new StringBuilder();
                    sb.append("**************************\nGarbage Collector invoked!\n**************************\n");
                    sb.append("GC Type: ").append(gctype).append("\n");
                    //sb.append("ID: ").append(info.getGcInfo().getId()).append("\n");
                    sb.append("Cause: ").append(info.getGcCause()).append("\n");
                    sb.append("Duration: ").append(info.getGcInfo().getDuration()).append(" ms\n");
                    
                    /*//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();
                    for (Entry<String, MemoryUsage> entry : mem.entrySet()) 
                    {
                        String name = entry.getKey();
                        MemoryUsage memdetail = entry.getValue();
                        long memInit = memdetail.getInit();
                        long memCommitted = memdetail.getCommitted();
                        long memMax = memdetail.getMax();
                        long memUsed = memdetail.getUsed();
                        MemoryUsage before = membefore.get(name);
                        long beforepercent = ((before.getUsed()*1000L)/before.getCommitted());
                        long percent = ((memUsed*1000L)/before.getCommitted()); //>100% when it gets expanded
                        
                        sb.append(name + (memCommitted==memMax?"(fully expanded)":"(still expandable)") +"used: "+(beforepercent/10)+"."+(beforepercent%10)+"%->"+(percent/10)+"."+(percent%10)+"%("+((memUsed/1048576)+1)+"MB) / \n");
                        
                    }*/
        
                    totalGcDuration += info.getGcInfo().getDuration();
                    long percent = totalGcDuration*1000L/info.getGcInfo().getEndTime();
                    sb.append("GC cumulated overhead "+(percent/10)+"."+(percent%10)+"%");
                    Debug.log(sb.append("\n").toString());
      
                }
    
            }
            
        };
        
        //Add the listener
        emitter.addNotificationListener(listener, null, null);

    }
    
}
 
Example 28
Project: G2Dj   File: GCTest.java   View Source Code Vote up 4 votes
public static void installGCMonitoring()
{
   //get all the GarbageCollectorMXBeans - there's one for each heap generation
   //so probably two - the old generation and young generation
   List<java.lang.management.GarbageCollectorMXBean> gcbeans = java.lang.management.ManagementFactory.getGarbageCollectorMXBeans();
   //Install a notifcation handler for each bean
   for (GarbageCollectorMXBean gcbean : gcbeans) 
   {
       System.out.println(gcbean);
       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());
                   
                   String gctype = info.getGcAction();
                   if ("end of minor GC".equals(gctype))
                       gctype = "Young Gen GC";
                   else if ("end of major GC".equals(gctype))
                       gctype = "Old Gen GC";
                   
                   StringBuilder sb = new StringBuilder();
                   sb.append("**************************\nGarbage Collector invoked!\n**************************\n");
                   sb.append("GC Type: ").append(gctype).append("\n");
                   sb.append("ID: ").append(info.getGcInfo().getId()).append("\n");
                   sb.append("Cause: ").append(info.getGcCause()).append("\n");
                   sb.append("Duration: ").append(info.getGcInfo().getDuration()).append(" ms\n");
                   
                   /*//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();
                   for (Entry<String, MemoryUsage> entry : mem.entrySet()) 
                   {
                       String name = entry.getKey();
                       MemoryUsage memdetail = entry.getValue();
                       long memInit = memdetail.getInit();
                       long memCommitted = memdetail.getCommitted();
                       long memMax = memdetail.getMax();
                       long memUsed = memdetail.getUsed();
                       MemoryUsage before = membefore.get(name);
                       long beforepercent = ((before.getUsed()*1000L)/before.getCommitted());
                       long percent = ((memUsed*1000L)/before.getCommitted()); //>100% when it gets expanded
                       
                       sb.append(name + (memCommitted==memMax?"(fully expanded)":"(still expandable)") +"used: "+(beforepercent/10)+"."+(beforepercent%10)+"%->"+(percent/10)+"."+(percent%10)+"%("+((memUsed/1048576)+1)+"MB) / \n");
                       
                   }*/
       
                   totalGcDuration += info.getGcInfo().getDuration();
                   long percent = totalGcDuration*1000L/info.getGcInfo().getEndTime();
                   sb.append("GC cumulated overhead "+(percent/10)+"."+(percent%10)+"%");
                   Debug.log(sb.append("\n").toString());
     
               }
   
           }
           
       };
       
       //Add the listener
       emitter.addNotificationListener(listener, null, null);

   }

}
 
Example 29
Project: OpenJSharp   File: JVM_MANAGEMENT_MIB_IMPL.java   View Source Code Vote up 4 votes
/**
 * 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);
}
 
Example 30
Project: jdk8u-jdk   File: JVM_MANAGEMENT_MIB_IMPL.java   View Source Code Vote up 4 votes
/**
 * 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);
}
 
Example 31
Project: jdk8u_jdk   File: JVM_MANAGEMENT_MIB_IMPL.java   View Source Code Vote up 4 votes
/**
 * 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);
}
 
Example 32
Project: lookaside_java-1.8.0-openjdk   File: JVM_MANAGEMENT_MIB_IMPL.java   View Source Code Vote up 4 votes
/**
 * 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);
}
 
Example 33
Project: dsl-devkit   File: VirtualMachineTracer.java   View Source Code Vote up 4 votes
/**
 * Installs a listener that will publish all full GC events as {@link FullGarbageCollectionEvent} objects.
 */
public void start() {
  // This code only works with Oracle HotSpot JVM as there is no standard API to retrieve information about GC events
  if (!isHotSpotVM()) {
    return;
  }

  long vmStartTime = getApproximateNanoStartTime();

  for (GarbageCollectorMXBean gcBean : ManagementFactory.getGarbageCollectorMXBeans()) {
    Class<? extends TraceEvent> eventType = gcBean.getName().equals("ConcurrentMarkSweep") || gcBean.getName().equals("MarkSweepCompact") //$NON-NLS-1$ //$NON-NLS-2$
        ? FullGarbageCollectionEvent.class
        : MinorGarbageCollectionEvent.class;
    NotificationEmitter emitter = (NotificationEmitter) gcBean;
    NotificationListener listener = new NotificationListener() {

      @Override
      public void handleNotification(final Notification notification, final Object handback) {
        try {
          // we only handle GARBAGE_COLLECTION_NOTIFICATION notifications here
          if (notification.getType().equals("com.sun.management.gc.notification")) { //$NON-NLS-1$
            CompositeData cd = (CompositeData) notification.getUserData();
            String gcAction = (String) cd.get("gcAction"); //$NON-NLS-1$
            String gcCause = (String) cd.get("gcCause"); //$NON-NLS-1$
            CompositeData gcInfo = (CompositeData) cd.get("gcInfo"); //$NON-NLS-1$
            long startTime = TimeUnit.NANOSECONDS.convert((Long) gcInfo.get("startTime"), TimeUnit.MILLISECONDS); //$NON-NLS-1$
            long duration = TimeUnit.NANOSECONDS.convert((Long) gcInfo.get("duration"), TimeUnit.MILLISECONDS); //$NON-NLS-1$
            if (duration > 0) {
              // "startTime" and "duration" are relative to VM start time
              traceSet.started(eventType, vmStartTime + startTime, gcAction, gcCause);
              traceSet.ended(eventType, vmStartTime + startTime + duration);
            }
          }
        } catch (InvalidKeyException e) {
          // ignore
        }
      };
    };
    emitter.addNotificationListener(listener, null, null);
    gcListenerMap.put(emitter, listener);
  }
}
 
Example 34
Project: FastAsyncWorldedit   File: Fawe.java   View Source Code Vote up 4 votes
private void setupMemoryListener() {
    if (Settings.IMP.MAX_MEMORY_PERCENT < 1 || Settings.IMP.MAX_MEMORY_PERCENT > 99) {
        return;
    }
    try {
        final MemoryMXBean memBean = ManagementFactory.getMemoryMXBean();
        final NotificationEmitter ne = (NotificationEmitter) memBean;

        ne.addNotificationListener(new NotificationListener() {
            @Override
            public void handleNotification(final Notification notification, final Object handback) {
                final long heapSize = Runtime.getRuntime().totalMemory();
                final long heapMaxSize = Runtime.getRuntime().maxMemory();
                if (heapSize < heapMaxSize) {
                    return;
                }
                MemUtil.memoryLimitedTask();
            }
        }, null, null);

        final List<MemoryPoolMXBean> memPools = ManagementFactory.getMemoryPoolMXBeans();
        for (final MemoryPoolMXBean mp : memPools) {
            if (mp.isUsageThresholdSupported()) {
                final MemoryUsage mu = mp.getUsage();
                final long max = mu.getMax();
                if (max < 0) {
                    continue;
                }
                final long alert = (max * Settings.IMP.MAX_MEMORY_PERCENT) / 100;
                mp.setUsageThreshold(alert);
            }
        }
    } catch (Throwable e) {
        debug("====== MEMORY LISTENER ERROR ======");
        MainUtil.handleError(e, false);
        debug("===================================");
        debug("FAWE needs access to the JVM memory system:");
        debug(" - Change your Java security settings");
        debug(" - Disable this with `max-memory-percent: -1`");
        debug("===================================");
    }
}
 
Example 35
Project: infobip-open-jdk-8   File: JVM_MANAGEMENT_MIB_IMPL.java   View Source Code Vote up 4 votes
/**
 * 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);
}
 
Example 36
Project: jdk8u-dev-jdk   File: JVM_MANAGEMENT_MIB_IMPL.java   View Source Code Vote up 4 votes
/**
 * 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);
}
 
Example 37
Project: jdk7-jdk   File: JVM_MANAGEMENT_MIB_IMPL.java   View Source Code Vote up 4 votes
/**
 * 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);
}
 
Example 38
Project: javase-study   File: ManagementTest.java   View Source Code Vote up 4 votes
public static void main(String[] args) {
  OperatingSystemMXBean mxBean = ManagementFactory.getOperatingSystemMXBean();
  System.out.println(mxBean.getSystemLoadAverage());

  ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
  System.out.println(threadMXBean.getAllThreadIds());
  System.out.println(threadMXBean.getCurrentThreadCpuTime());
  System.out.println(threadMXBean.getCurrentThreadUserTime());

  MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean();
  System.out.println(memoryMXBean.getHeapMemoryUsage());
  System.out.println(memoryMXBean.getNonHeapMemoryUsage());
  System.out.println(memoryMXBean.getObjectPendingFinalizationCount());

  for (MemoryManagerMXBean memoryManagerMXBean : ManagementFactory.getMemoryManagerMXBeans()) {
    System.out.println(memoryManagerMXBean.getName());
  }


  NotificationListener notificationListener = new NotificationListener() {
    public void handleNotification(Notification notification, Object handback) {
      if (notification.getType().equals(GarbageCollectionNotificationInfo
                                                .GARBAGE_COLLECTION_NOTIFICATION)) {
        GarbageCollectionNotificationInfo gcInfo = GarbageCollectionNotificationInfo.from
                ((CompositeData) notification.getUserData());
        System.out.println(gcInfo.getGcName());
        System.out.println(gcInfo.getGcInfo().getMemoryUsageBeforeGc());
        System.out.println(gcInfo.getGcInfo().getMemoryUsageAfterGc());

        for (MemoryUsage memoryUsage : gcInfo.getGcInfo().getMemoryUsageBeforeGc().values()) {
          System.out.println(memoryUsage.getUsed());
        }
      }
    }
  };
  for (GarbageCollectorMXBean gcBean : ManagementFactory.getGarbageCollectorMXBeans()) {
    NotificationEmitter emitter = (NotificationEmitter) gcBean;
    emitter.addNotificationListener(notificationListener, null, null);
  }
  while (true) {

  }
}
 
Example 39
Project: openjdk-source-code-learn   File: JVM_MANAGEMENT_MIB_IMPL.java   View Source Code Vote up 4 votes
/**
 * 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);
}
 
Example 40
Project: OLD-OpenJDK8   File: JVM_MANAGEMENT_MIB_IMPL.java   View Source Code Vote up 4 votes
/**
 * 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);
}
 
Example 41
Project: tigase-server   File: MemMonitor.java   View Source Code Vote up 4 votes
@Override
public void init(JID jid, float treshold, SystemMonitorTask smTask) {
	super.init(jid, treshold, smTask);
	memoryMXBean = ManagementFactory.getMemoryMXBean();
	NotificationEmitter emitter = (NotificationEmitter)memoryMXBean;
	List<MemoryPoolMXBean> memPools = ManagementFactory.getMemoryPoolMXBeans();
	for (MemoryPoolMXBean memoryPoolMXBean : memPools) {
		try {
			emitter.removeNotificationListener(this, null, memoryPoolMXBean);
		} catch (Exception e) {	}
		MemoryUsage memUsage = memoryPoolMXBean.getUsage();
		if (memUsage != null) {
			if (memoryPoolMXBean.isUsageThresholdSupported()) {
				emitter.addNotificationListener(this, null, memoryPoolMXBean);
				long memUsageTreshold =
								new Double(new Long(memUsage.getMax()).doubleValue() *
								treshold).longValue();
				memoryPoolMXBean.setUsageThreshold(memUsageTreshold);
				log.config("Setting treshold: " + memUsageTreshold +
								" for memory pool: " + memoryPoolMXBean.getName() +
								", type: " + memoryPoolMXBean.getType().toString() +
								", memMax: " + memUsage.getMax() +
								", memUsed: " + memUsage.getUsed() +
								", config treeshold: " + treshold);
				if (memUsage.getUsed() > memUsageTreshold) {
					Notification not = new Notification(
									MemoryNotificationInfo.MEMORY_THRESHOLD_EXCEEDED,
									this, 1);
					handleNotification(not, memoryPoolMXBean);
				}
			} else {
				log.config("Memory pool name: " + memoryPoolMXBean.getName() +
								", type: " + memoryPoolMXBean.getType().toString() +
								" usage threshold is not supported.");
			}
		} else {
			log.config("Memory pool name: " + memoryPoolMXBean.getName() +
							", type: " + memoryPoolMXBean.getType().toString() +
							" is invalid.");
		}
	}
}
 
Example 42
Project: openjdk-jdk7u-jdk   File: JVM_MANAGEMENT_MIB_IMPL.java   View Source Code Vote up 4 votes
/**
 * 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);
}
 
Example 43
Project: nyla   File: JMX.java   View Source Code Vote up 3 votes
/**
   * Allows a listener to be registered within the MemoryMXBean as a notification listener
   * usage threshold exceeded notification - for notifying that the memory usage of a memory pool is increased 
   * and has reached or exceeded its usage threshold value.
   * 
   * collection usage threshold exceeded notification - for notifying that the memory usage 
   * of a memory pool is greater than or equal to its collection usage threshold 
   * after the Java virtual machine has expended effort in recycling unused objects in that memory pool.
   * 
   * The notification emitted is a Notification instance whose user data is set to a CompositeData that 
   * represents a MemoryNotificationInfo object containing information about the memory pool when the 
   * notification was constructed. The CompositeData contains the attributes as described in MemoryNotificationInfo.
   * 
   * @param notificationListener listener to be alerted
   * @param handback object to be passed back to notification listener when notification occurs
   */
  public void registerMemoryNotifications(NotificationListener notificationListener, Object handback)
  {
NotificationEmitter emitter = (NotificationEmitter) this.getMemory();
emitter.addNotificationListener(notificationListener, null, handback);

  }