Java Code Examples for javax.management.NotificationEmitter

The following are top voted examples for showing how to use javax.management.NotificationEmitter. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: otus_java_2017_06   File: Main.java   View source code 6 votes vote down vote up
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 6 votes vote down vote up
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 6 votes vote down vote up
/**
 * 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: jdk8u-jdk   File: TestUtils.java   View source code 6 votes vote down vote up
/**
 * Transfroms a proxy implementing T in a proxy implementing T plus
 * NotificationEmitter
 *
 **/
public static <T> T makeNotificationEmitter(T proxy,
                    Class<T> mbeanInterface) {
    if (proxy instanceof NotificationEmitter)
        return proxy;
    if (proxy == null) return null;
    if (!(proxy instanceof Proxy))
        throw new IllegalArgumentException("not a "+Proxy.class.getName());
    final Proxy p = (Proxy) proxy;
    final InvocationHandler handler =
            Proxy.getInvocationHandler(proxy);
    if (!(handler instanceof MBeanServerInvocationHandler))
        throw new IllegalArgumentException("not a JMX Proxy");
    final MBeanServerInvocationHandler h =
            (MBeanServerInvocationHandler)handler;
    final ObjectName name = h.getObjectName();
    final MBeanServerConnection mbs = h.getMBeanServerConnection();
    final boolean isMXBean = h.isMXBean();
    final T newProxy;
    if (isMXBean)
        newProxy = JMX.newMXBeanProxy(mbs,name,mbeanInterface,true);
    else
        newProxy = JMX.newMBeanProxy(mbs,name,mbeanInterface,true);
    return newProxy;
}
 
Example 5
Project: openjdk-jdk10   File: ThresholdNotificationsTest.java   View source code 6 votes vote down vote up
protected void runTest() {
    int iterationsCount
            = Integer.getInteger("jdk.test.lib.iterations", 1);
    MemoryPoolMXBean bean = btype.getMemoryPool();
    ((NotificationEmitter) ManagementFactory.getMemoryMXBean()).
            addNotificationListener(this, null, null);
    for (int i = 0; i < iterationsCount; i++) {
        CodeCacheUtils.hitUsageThreshold(bean, btype);
    }
    Asserts.assertTrue(
            Utils.waitForCondition(
                    () -> (CodeCacheUtils.isCodeHeapPredictable(btype) ?
                            (counter == iterationsCount) : (counter >= iterationsCount)),
                    WAIT_TIME),
            "Couldn't receive expected notifications count");
    try {
        ((NotificationEmitter) ManagementFactory.getMemoryMXBean()).
                removeNotificationListener(this);
    } catch (ListenerNotFoundException ex) {
        throw new AssertionError("Can't remove notification listener", ex);
    }
    System.out.printf("INFO: Scenario finished successfully for %s%n",
            bean.getName());
}
 
Example 6
Project: openjdk9   File: ThresholdNotificationsTest.java   View source code 6 votes vote down vote up
protected void runTest() {
    int iterationsCount =
        Integer.getInteger("jdk.test.lib.iterations", 1);
    MemoryPoolMXBean bean = btype.getMemoryPool();
    ((NotificationEmitter) ManagementFactory.getMemoryMXBean()).
            addNotificationListener(this, null, null);
    for (int i = 0; i < iterationsCount; i++) {
        CodeCacheUtils.hitUsageThreshold(bean, btype);
    }
    Asserts.assertTrue(
            Utils.waitForCondition(
                    () -> (CodeCacheUtils.isCodeHeapPredictable(btype) ?
                            (counter == iterationsCount) : (counter >= iterationsCount)),
                    WAIT_TIME),
            "Couldn't receive expected notifications count");
    try {
        ((NotificationEmitter) ManagementFactory.getMemoryMXBean()).
                removeNotificationListener(this);
    } catch (ListenerNotFoundException ex) {
        throw new AssertionError("Can't remove notification listener", ex);
    }
    System.out.printf("INFO: Scenario finished successfully for %s%n",
            bean.getName());
}
 
Example 7
Project: openjdk9   File: TestUtils.java   View source code 6 votes vote down vote up
/**
 * Transfroms a proxy implementing T in a proxy implementing T plus
 * NotificationEmitter
 *
 **/
public static <T> T makeNotificationEmitter(T proxy,
                    Class<T> mbeanInterface) {
    if (proxy instanceof NotificationEmitter)
        return proxy;
    if (proxy == null) return null;
    if (!(proxy instanceof Proxy))
        throw new IllegalArgumentException("not a "+Proxy.class.getName());
    final Proxy p = (Proxy) proxy;
    final InvocationHandler handler =
            Proxy.getInvocationHandler(proxy);
    if (!(handler instanceof MBeanServerInvocationHandler))
        throw new IllegalArgumentException("not a JMX Proxy");
    final MBeanServerInvocationHandler h =
            (MBeanServerInvocationHandler)handler;
    final ObjectName name = h.getObjectName();
    final MBeanServerConnection mbs = h.getMBeanServerConnection();
    final boolean isMXBean = h.isMXBean();
    final T newProxy;
    if (isMXBean)
        newProxy = JMX.newMXBeanProxy(mbs,name,mbeanInterface,true);
    else
        newProxy = JMX.newMBeanProxy(mbs,name,mbeanInterface,true);
    return newProxy;
}
 
Example 8
Project: jdk8u_jdk   File: TestUtils.java   View source code 6 votes vote down vote up
/**
 * Transfroms a proxy implementing T in a proxy implementing T plus
 * NotificationEmitter
 *
 **/
public static <T> T makeNotificationEmitter(T proxy,
                    Class<T> mbeanInterface) {
    if (proxy instanceof NotificationEmitter)
        return proxy;
    if (proxy == null) return null;
    if (!(proxy instanceof Proxy))
        throw new IllegalArgumentException("not a "+Proxy.class.getName());
    final Proxy p = (Proxy) proxy;
    final InvocationHandler handler =
            Proxy.getInvocationHandler(proxy);
    if (!(handler instanceof MBeanServerInvocationHandler))
        throw new IllegalArgumentException("not a JMX Proxy");
    final MBeanServerInvocationHandler h =
            (MBeanServerInvocationHandler)handler;
    final ObjectName name = h.getObjectName();
    final MBeanServerConnection mbs = h.getMBeanServerConnection();
    final boolean isMXBean = h.isMXBean();
    final T newProxy;
    if (isMXBean)
        newProxy = JMX.newMXBeanProxy(mbs,name,mbeanInterface,true);
    else
        newProxy = JMX.newMBeanProxy(mbs,name,mbeanInterface,true);
    return newProxy;
}
 
Example 9
Project: lookaside_java-1.8.0-openjdk   File: TestUtils.java   View source code 6 votes vote down vote up
/**
 * Transfroms a proxy implementing T in a proxy implementing T plus
 * NotificationEmitter
 *
 **/
public static <T> T makeNotificationEmitter(T proxy,
                    Class<T> mbeanInterface) {
    if (proxy instanceof NotificationEmitter)
        return proxy;
    if (proxy == null) return null;
    if (!(proxy instanceof Proxy))
        throw new IllegalArgumentException("not a "+Proxy.class.getName());
    final Proxy p = (Proxy) proxy;
    final InvocationHandler handler =
            Proxy.getInvocationHandler(proxy);
    if (!(handler instanceof MBeanServerInvocationHandler))
        throw new IllegalArgumentException("not a JMX Proxy");
    final MBeanServerInvocationHandler h =
            (MBeanServerInvocationHandler)handler;
    final ObjectName name = h.getObjectName();
    final MBeanServerConnection mbs = h.getMBeanServerConnection();
    final boolean isMXBean = h.isMXBean();
    final T newProxy;
    if (isMXBean)
        newProxy = JMX.newMXBeanProxy(mbs,name,mbeanInterface,true);
    else
        newProxy = JMX.newMBeanProxy(mbs,name,mbeanInterface,true);
    return newProxy;
}
 
Example 10
Project: kc-rice   File: MemoryMonitor.java   View source code 6 votes vote down vote up
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 11
Project: SOMns   File: ActorExecutionTrace.java   View source code 6 votes vote down vote up
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 12
Project: Advanced-Trigoplex   File: TestUtils.java   View source code 6 votes vote down vote up
/**
 * Transfroms a proxy implementing T in a proxy implementing T plus
 * NotificationEmitter
 *
 **/
public static <T> T makeNotificationEmitter(T proxy,
                    Class<T> mbeanInterface) {
    if (proxy instanceof NotificationEmitter)
        return proxy;
    if (proxy == null) return null;
    if (!(proxy instanceof Proxy))
        throw new IllegalArgumentException("not a "+Proxy.class.getName());
    final Proxy p = (Proxy) proxy;
    final InvocationHandler handler =
            Proxy.getInvocationHandler(proxy);
    if (!(handler instanceof MBeanServerInvocationHandler))
        throw new IllegalArgumentException("not a JMX Proxy");
    final MBeanServerInvocationHandler h =
            (MBeanServerInvocationHandler)handler;
    final ObjectName name = h.getObjectName();
    final MBeanServerConnection mbs = h.getMBeanServerConnection();
    final boolean isMXBean = h.isMXBean();
    final T newProxy;
    if (isMXBean)
        newProxy = JMX.newMXBeanProxy(mbs,name,mbeanInterface,true);
    else
        newProxy = JMX.newMBeanProxy(mbs,name,mbeanInterface,true);
    return newProxy;
}
 
Example 13
Project: Lucee4   File: MemoryControler.java   View source code 6 votes vote down vote up
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 14
Project: infobip-open-jdk-8   File: TestUtils.java   View source code 6 votes vote down vote up
/**
 * Transfroms a proxy implementing T in a proxy implementing T plus
 * NotificationEmitter
 *
 **/
public static <T> T makeNotificationEmitter(T proxy,
                    Class<T> mbeanInterface) {
    if (proxy instanceof NotificationEmitter)
        return proxy;
    if (proxy == null) return null;
    if (!(proxy instanceof Proxy))
        throw new IllegalArgumentException("not a "+Proxy.class.getName());
    final Proxy p = (Proxy) proxy;
    final InvocationHandler handler =
            Proxy.getInvocationHandler(proxy);
    if (!(handler instanceof MBeanServerInvocationHandler))
        throw new IllegalArgumentException("not a JMX Proxy");
    final MBeanServerInvocationHandler h =
            (MBeanServerInvocationHandler)handler;
    final ObjectName name = h.getObjectName();
    final MBeanServerConnection mbs = h.getMBeanServerConnection();
    final boolean isMXBean = h.isMXBean();
    final T newProxy;
    if (isMXBean)
        newProxy = JMX.newMXBeanProxy(mbs,name,mbeanInterface,true);
    else
        newProxy = JMX.newMBeanProxy(mbs,name,mbeanInterface,true);
    return newProxy;
}
 
Example 15
Project: jdk8u-dev-jdk   File: TestUtils.java   View source code 6 votes vote down vote up
/**
 * Transfroms a proxy implementing T in a proxy implementing T plus
 * NotificationEmitter
 *
 **/
public static <T> T makeNotificationEmitter(T proxy,
                    Class<T> mbeanInterface) {
    if (proxy instanceof NotificationEmitter)
        return proxy;
    if (proxy == null) return null;
    if (!(proxy instanceof Proxy))
        throw new IllegalArgumentException("not a "+Proxy.class.getName());
    final Proxy p = (Proxy) proxy;
    final InvocationHandler handler =
            Proxy.getInvocationHandler(proxy);
    if (!(handler instanceof MBeanServerInvocationHandler))
        throw new IllegalArgumentException("not a JMX Proxy");
    final MBeanServerInvocationHandler h =
            (MBeanServerInvocationHandler)handler;
    final ObjectName name = h.getObjectName();
    final MBeanServerConnection mbs = h.getMBeanServerConnection();
    final boolean isMXBean = h.isMXBean();
    final T newProxy;
    if (isMXBean)
        newProxy = JMX.newMXBeanProxy(mbs,name,mbeanInterface,true);
    else
        newProxy = JMX.newMBeanProxy(mbs,name,mbeanInterface,true);
    return newProxy;
}
 
Example 16
Project: Lucee   File: MemoryControler.java   View source code 6 votes vote down vote up
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 17
Project: jdk7-jdk   File: TestUtils.java   View source code 6 votes vote down vote up
/**
 * Transfroms a proxy implementing T in a proxy implementing T plus
 * NotificationEmitter
 *
 **/
public static <T> T makeNotificationEmitter(T proxy,
                    Class<T> mbeanInterface) {
    if (proxy instanceof NotificationEmitter)
        return proxy;
    if (proxy == null) return null;
    if (!(proxy instanceof Proxy))
        throw new IllegalArgumentException("not a "+Proxy.class.getName());
    final Proxy p = (Proxy) proxy;
    final InvocationHandler handler =
            Proxy.getInvocationHandler(proxy);
    if (!(handler instanceof MBeanServerInvocationHandler))
        throw new IllegalArgumentException("not a JMX Proxy");
    final MBeanServerInvocationHandler h =
            (MBeanServerInvocationHandler)handler;
    final ObjectName name = h.getObjectName();
    final MBeanServerConnection mbs = h.getMBeanServerConnection();
    final boolean isMXBean = h.isMXBean();
    final T newProxy;
    if (isMXBean)
        newProxy = JMX.newMXBeanProxy(mbs,name,mbeanInterface,true);
    else
        newProxy = JMX.newMBeanProxy(mbs,name,mbeanInterface,true);
    return newProxy;
}
 
Example 18
Project: openjdk-source-code-learn   File: TestUtils.java   View source code 6 votes vote down vote up
/**
 * Transfroms a proxy implementing T in a proxy implementing T plus
 * NotificationEmitter
 *
 **/
public static <T> T makeNotificationEmitter(T proxy,
                    Class<T> mbeanInterface) {
    if (proxy instanceof NotificationEmitter)
        return proxy;
    if (proxy == null) return null;
    if (!(proxy instanceof Proxy))
        throw new IllegalArgumentException("not a "+Proxy.class.getName());
    final Proxy p = (Proxy) proxy;
    final InvocationHandler handler =
            Proxy.getInvocationHandler(proxy);
    if (!(handler instanceof MBeanServerInvocationHandler))
        throw new IllegalArgumentException("not a JMX Proxy");
    final MBeanServerInvocationHandler h =
            (MBeanServerInvocationHandler)handler;
    final ObjectName name = h.getObjectName();
    final MBeanServerConnection mbs = h.getMBeanServerConnection();
    final boolean isMXBean = h.isMXBean();
    final T newProxy;
    if (isMXBean)
        newProxy = JMX.newMXBeanProxy(mbs,name,mbeanInterface,true);
    else
        newProxy = JMX.newMBeanProxy(mbs,name,mbeanInterface,true);
    return newProxy;
}
 
Example 19
Project: OLE-INST   File: MemoryMonitor.java   View source code 6 votes vote down vote up
public MemoryMonitor() {
    LOG.info("initializing");
    this.springContextId = "Unknown";
    ManagementFactory.getThreadMXBean().setThreadContentionMonitoringEnabled(true);
    ManagementFactory.getThreadMXBean().setThreadCpuTimeEnabled(true);
    lowMemoryListener = new NotificationListener() {
        public void handleNotification(Notification n, Object hb) {
            if (n.getType().equals(MemoryNotificationInfo.MEMORY_THRESHOLD_EXCEEDED)) {
                Map<String, String> memoryUsageStatistics = new HashMap<String, String>();
                memoryUsageStatistics.put("MemoryMXBean: " + MemoryType.HEAP, ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().toString());
                memoryUsageStatistics.put("MemoryMXBean:" + MemoryType.NON_HEAP, ManagementFactory.getMemoryMXBean().getNonHeapMemoryUsage().toString());
                for (MemoryPoolMXBean pool : ManagementFactory.getMemoryPoolMXBeans()) {
                    memoryUsageStatistics.put("MemoryPoolMXBean: " + pool.getType(), pool.getUsage().toString());
                }
                for (Listener listener : listeners) {
                    listener.memoryUsageLow(springContextId, memoryUsageStatistics, Arrays.toString(ManagementFactory.getThreadMXBean().findMonitorDeadlockedThreads()));
                }
            }
        }
    };
    ((NotificationEmitter) ManagementFactory.getMemoryMXBean()).addNotificationListener(lowMemoryListener, null, null);
}
 
Example 20
Project: spectator   File: GcLogger.java   View source code 6 votes vote down vote up
/**
 * 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 21
Project: OLD-OpenJDK8   File: TestUtils.java   View source code 6 votes vote down vote up
/**
 * Transfroms a proxy implementing T in a proxy implementing T plus
 * NotificationEmitter
 *
 **/
public static <T> T makeNotificationEmitter(T proxy,
                    Class<T> mbeanInterface) {
    if (proxy instanceof NotificationEmitter)
        return proxy;
    if (proxy == null) return null;
    if (!(proxy instanceof Proxy))
        throw new IllegalArgumentException("not a "+Proxy.class.getName());
    final Proxy p = (Proxy) proxy;
    final InvocationHandler handler =
            Proxy.getInvocationHandler(proxy);
    if (!(handler instanceof MBeanServerInvocationHandler))
        throw new IllegalArgumentException("not a JMX Proxy");
    final MBeanServerInvocationHandler h =
            (MBeanServerInvocationHandler)handler;
    final ObjectName name = h.getObjectName();
    final MBeanServerConnection mbs = h.getMBeanServerConnection();
    final boolean isMXBean = h.isMXBean();
    final T newProxy;
    if (isMXBean)
        newProxy = JMX.newMXBeanProxy(mbs,name,mbeanInterface,true);
    else
        newProxy = JMX.newMBeanProxy(mbs,name,mbeanInterface,true);
    return newProxy;
}
 
Example 22
Project: cn1   File: ManagementFactory.java   View source code 6 votes vote down vote up
/**
 * @param <T>
 * @param connection
 * @param mxbeanName
 * @param mxbeanInterface
 * @return a new proxy object representing the named <code>MXBean</code>.
 *         All subsequent method invocations on the proxy will be routed
 *         through the supplied {@link MBeanServerConnection} object.
 * @throws IOException
 */
@SuppressWarnings("unchecked")
public static <T> T newPlatformMXBeanProxy(MBeanServerConnection connection,
        String mxbeanName, Class<T> mxbeanInterface) throws IOException {
    // Check that the named object implements the specified interface
    verifyNamedMXBean(mxbeanName, mxbeanInterface);

    T result = null;
    Class[] interfaces = null;
    if (ManagementUtils.isANotificationEmitter(mxbeanInterface)) {
        // Proxies of the MemoryMXBean and OperatingSystemMXBean interfaces
        // must also implement the NotificationEmitter interface.
        interfaces = new Class[] { mxbeanInterface,
                NotificationEmitter.class };
    } else {
        interfaces = new Class[] { mxbeanInterface };
    }

    result = (T) Proxy.newProxyInstance(interfaces[0].getClassLoader(),
            interfaces, new OpenTypeMappingIHandler(connection,
                    mxbeanInterface.getName(), mxbeanName));
    return result;
}
 
Example 23
Project: kfs   File: MemoryMonitor.java   View source code 6 votes vote down vote up
public MemoryMonitor() {
    LOG.info("initializing");
    this.springContextId = "Unknown";
    ManagementFactory.getThreadMXBean().setThreadContentionMonitoringEnabled(true);
    ManagementFactory.getThreadMXBean().setThreadCpuTimeEnabled(true);
    lowMemoryListener = new NotificationListener() {
        public void handleNotification(Notification n, Object hb) {
            if (n.getType().equals(MemoryNotificationInfo.MEMORY_THRESHOLD_EXCEEDED)) {
                Map<String, String> memoryUsageStatistics = new HashMap<String, String>();
                memoryUsageStatistics.put("MemoryMXBean: " + MemoryType.HEAP, ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().toString());
                memoryUsageStatistics.put("MemoryMXBean:" + MemoryType.NON_HEAP, ManagementFactory.getMemoryMXBean().getNonHeapMemoryUsage().toString());
                for (MemoryPoolMXBean pool : ManagementFactory.getMemoryPoolMXBeans()) {
                    memoryUsageStatistics.put("MemoryPoolMXBean: " + pool.getType(), pool.getUsage().toString());
                }
                for (Listener listener : listeners) {
                    listener.memoryUsageLow(springContextId, memoryUsageStatistics, Arrays.toString(ManagementFactory.getThreadMXBean().findMonitorDeadlockedThreads()));
                }
            }
        }
    };
    ((NotificationEmitter) ManagementFactory.getMemoryMXBean()).addNotificationListener(lowMemoryListener, null, null);
}
 
Example 24
Project: pitest   File: MemoryWatchdog.java   View source code 6 votes vote down vote up
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 25
Project: bazel   File: RetainedHeapLimiter.java   View source code 6 votes vote down vote up
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 26
Project: openjdk-jdk7u-jdk   File: TestUtils.java   View source code 6 votes vote down vote up
/**
 * Transfroms a proxy implementing T in a proxy implementing T plus
 * NotificationEmitter
 *
 **/
public static <T> T makeNotificationEmitter(T proxy,
                    Class<T> mbeanInterface) {
    if (proxy instanceof NotificationEmitter)
        return proxy;
    if (proxy == null) return null;
    if (!(proxy instanceof Proxy))
        throw new IllegalArgumentException("not a "+Proxy.class.getName());
    final Proxy p = (Proxy) proxy;
    final InvocationHandler handler =
            Proxy.getInvocationHandler(proxy);
    if (!(handler instanceof MBeanServerInvocationHandler))
        throw new IllegalArgumentException("not a JMX Proxy");
    final MBeanServerInvocationHandler h =
            (MBeanServerInvocationHandler)handler;
    final ObjectName name = h.getObjectName();
    final MBeanServerConnection mbs = h.getMBeanServerConnection();
    final boolean isMXBean = h.isMXBean();
    final T newProxy;
    if (isMXBean)
        newProxy = JMX.newMXBeanProxy(mbs,name,mbeanInterface,true);
    else
        newProxy = JMX.newMBeanProxy(mbs,name,mbeanInterface,true);
    return newProxy;
}
 
Example 27
Project: rice   File: MemoryMonitor.java   View source code 6 votes vote down vote up
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 28
Project: freeVM   File: ManagementFactory.java   View source code 6 votes vote down vote up
/**
 * @param <T>
 * @param connection
 * @param mxbeanName
 * @param mxbeanInterface
 * @return a new proxy object representing the named <code>MXBean</code>.
 *         All subsequent method invocations on the proxy will be routed
 *         through the supplied {@link MBeanServerConnection} object.
 * @throws IOException
 */
@SuppressWarnings("unchecked")
public static <T> T newPlatformMXBeanProxy(MBeanServerConnection connection,
        String mxbeanName, Class<T> mxbeanInterface) throws IOException {
    // Check that the named object implements the specified interface
    verifyNamedMXBean(mxbeanName, mxbeanInterface);

    T result = null;
    Class[] interfaces = null;
    if (ManagementUtils.isANotificationEmitter(mxbeanInterface)) {
        // Proxies of the MemoryMXBean and OperatingSystemMXBean interfaces
        // must also implement the NotificationEmitter interface.
        interfaces = new Class[] { mxbeanInterface,
                NotificationEmitter.class };
    } else {
        interfaces = new Class[] { mxbeanInterface };
    }

    result = (T) Proxy.newProxyInstance(interfaces[0].getClassLoader(),
            interfaces, new OpenTypeMappingIHandler(connection,
                    mxbeanInterface.getName(), mxbeanName));
    return result;
}
 
Example 29
Project: freeVM   File: ManagementFactory.java   View source code 6 votes vote down vote up
/**
 * @param <T>
 * @param connection
 * @param mxbeanName
 * @param mxbeanInterface
 * @return a new proxy object representing the named <code>MXBean</code>.
 *         All subsequent method invocations on the proxy will be routed
 *         through the supplied {@link MBeanServerConnection} object.
 * @throws IOException
 */
@SuppressWarnings("unchecked")
public static <T> T newPlatformMXBeanProxy(MBeanServerConnection connection,
        String mxbeanName, Class<T> mxbeanInterface) throws IOException {
    // Check that the named object implements the specified interface
    verifyNamedMXBean(mxbeanName, mxbeanInterface);

    T result = null;
    Class[] interfaces = null;
    if (ManagementUtils.isANotificationEmitter(mxbeanInterface)) {
        // Proxies of the MemoryMXBean and OperatingSystemMXBean interfaces
        // must also implement the NotificationEmitter interface.
        interfaces = new Class[] { mxbeanInterface,
                NotificationEmitter.class };
    } else {
        interfaces = new Class[] { mxbeanInterface };
    }

    result = (T) Proxy.newProxyInstance(interfaces[0].getClassLoader(),
            interfaces, new OpenTypeMappingIHandler(connection,
                    mxbeanInterface.getName(), mxbeanName));
    return result;
}
 
Example 30
Project: openjdk-icedtea7   File: TestUtils.java   View source code 6 votes vote down vote up
/**
 * Transfroms a proxy implementing T in a proxy implementing T plus
 * NotificationEmitter
 *
 **/
public static <T> T makeNotificationEmitter(T proxy,
                    Class<T> mbeanInterface) {
    if (proxy instanceof NotificationEmitter)
        return proxy;
    if (proxy == null) return null;
    if (!(proxy instanceof Proxy))
        throw new IllegalArgumentException("not a "+Proxy.class.getName());
    final Proxy p = (Proxy) proxy;
    final InvocationHandler handler =
            Proxy.getInvocationHandler(proxy);
    if (!(handler instanceof MBeanServerInvocationHandler))
        throw new IllegalArgumentException("not a JMX Proxy");
    final MBeanServerInvocationHandler h =
            (MBeanServerInvocationHandler)handler;
    final ObjectName name = h.getObjectName();
    final MBeanServerConnection mbs = h.getMBeanServerConnection();
    final boolean isMXBean = h.isMXBean();
    final T newProxy;
    if (isMXBean)
        newProxy = JMX.newMXBeanProxy(mbs,name,mbeanInterface,true);
    else
        newProxy = JMX.newMBeanProxy(mbs,name,mbeanInterface,true);
    return newProxy;
}
 
Example 31
Project: WBSAirback   File: TestUtils.java   View source code 6 votes vote down vote up
/**
 * Transfroms a proxy implementing T in a proxy implementing T plus
 * NotificationEmitter
 *
 **/
public static <T> T makeNotificationEmitter(T proxy,
                    Class<T> mbeanInterface) {
    if (proxy instanceof NotificationEmitter)
        return proxy;
    if (proxy == null) return null;
    if (!(proxy instanceof Proxy))
        throw new IllegalArgumentException("not a "+Proxy.class.getName());
    final Proxy p = (Proxy) proxy;
    final InvocationHandler handler =
            Proxy.getInvocationHandler(proxy);
    if (!(handler instanceof MBeanServerInvocationHandler))
        throw new IllegalArgumentException("not a JMX Proxy");
    final MBeanServerInvocationHandler h =
            (MBeanServerInvocationHandler)handler;
    final ObjectName name = h.getObjectName();
    final MBeanServerConnection mbs = h.getMBeanServerConnection();
    final boolean isMXBean = h.isMXBean();
    final T newProxy;
    if (isMXBean)
        newProxy = JMX.newMXBeanProxy(mbs,name,mbeanInterface,true);
    else
        newProxy = JMX.newMBeanProxy(mbs,name,mbeanInterface,true);
    return newProxy;
}
 
Example 32
Project: scaleDOM   File: LowMemoryDetector.java   View source code 6 votes vote down vote up
/**
 * 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 33
Project: java-perv   File: G1Demo.java   View source code 6 votes vote down vote up
private static void subscribeForGc() {
        ManagementFactory.getGarbageCollectorMXBeans().stream().filter(bean -> bean instanceof NotificationEmitter).forEach(bean -> {
            ((NotificationEmitter) bean).addNotificationListener((notification, handback) -> {
//                System.err.println("Notified");
                if (GARBAGE_COLLECTION_NOTIFICATION.equals(notification.getType())) {
                    GarbageCollectionNotificationInfo info = from((CompositeData) notification.getUserData());
                    com.sun.management.GarbageCollectorMXBean mxBean = (com.sun.management.GarbageCollectorMXBean) handback;

//                    System.err.println("GC notification");

                    GcInfo gcInfo = info.getGcInfo();
                    if (gcInfo != null) {

                        System.out.println(info.getGcName() + ", " + info.getGcAction() + ", " + mxBean.getName() + ", " + info.getGcCause() + ", " + gcInfo.getMemoryUsageBeforeGc() + ", " + gcInfo.getMemoryUsageAfterGc());
                    }
                }
            }, null, bean);
        });
    }
 
Example 34
Project: kuali_rice   File: MemoryMonitor.java   View source code 6 votes vote down vote up
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 35
Project: consulo   File: PerformanceWatcher.java   View source code 6 votes vote down vote up
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 36
Project: btrace   File: BTraceRuntime.java   View source code 6 votes vote down vote up
private synchronized void exitImpl(int exitCode) {
    if (exitHandler != null) {
        try {
            exitHandler.invoke(null, exitCode);
        } catch (Throwable ignored) {
        }
    }
    disabled = true;
    if (timer != null) {
        timer.cancel();
    }

    if (memoryListener != null && memoryMBean != null) {
        NotificationEmitter emitter = (NotificationEmitter) memoryMBean;
        try {
            emitter.removeNotificationListener(memoryListener);
        } catch (ListenerNotFoundException lnfe) {}
    }

    if (threadPool != null) {
        threadPool.shutdownNow();
    }

    send(new ExitCommand(exitCode));
}
 
Example 37
Project: monarch   File: HeapMemoryMonitor.java   View source code 5 votes vote down vote up
/**
 * Stops all three mechanisms from monitoring heap usage.
 */
@Override
public void stopMonitoring() {
  synchronized (this) {
    if (!this.started) {
      return;
    }

    // Stop the poller
    this.resourceManager.stopExecutor(this.pollerExecutor);

    // Stop the JVM threshold listener
    NotificationEmitter emitter = (NotificationEmitter) ManagementFactory.getMemoryMXBean();
    try {
      emitter.removeNotificationListener(this, null, null);
      this.cache.getLoggerI18n().fine("Removed Memory MXBean notification listener" + this);
    } catch (ListenerNotFoundException e) {
      this.cache.getLoggerI18n().fine(
          "This instance '" + toString() + "' was not registered as a Memory MXBean listener");
    }

    // Stop the stats listener
    final GemFireStatSampler sampler = this.cache.getDistributedSystem().getStatSampler();
    if (sampler != null) {
      sampler.removeLocalStatListener(this.statListener);
    }

    this.started = false;
  }
}
 
Example 38
Project: ChronoBike   File: CodeManager.java   View source code 5 votes vote down vote up
public static CodeSizeLimitEventHandler createSizeLimitEventHandler()
{
	MemoryMXBean mbean = ManagementFactory.getMemoryMXBean();
	NotificationEmitter emitter = (NotificationEmitter) mbean;
	CodeSizeLimitEventHandler eventHandler = new CodeSizeLimitEventHandler();
	return eventHandler;
}
 
Example 39
Project: jdk8u-jdk   File: ScanDirAgent.java   View source code 5 votes vote down vote up
/**
 * Initialize the application by registering a ScanManagerMXBean in
 * the platform MBeanServer
 * @throws java.io.IOException Registration failed for communication-related reasons.
 * @throws javax.management.JMException Registration failed for JMX-related reasons.
 */
public void init() throws IOException, JMException {

    // Registers the ScanManagerMXBean singleton in the
    // platform MBeanServer
    //
    proxy = ScanManager.register();

    // Registers a NotificationListener with the ScanManagerMXBean in
    // order to receive state changed notifications.
    //
    ((NotificationEmitter)proxy).addNotificationListener(listener,null,null);
}
 
Example 40
Project: jdk8u-jdk   File: ScanDirAgent.java   View source code 5 votes vote down vote up
/**
 * Cleanup after close: unregister the ScanManagerMXBean singleton.
 * @throws java.io.IOException Cleanup failed for communication-related reasons.
 * @throws javax.management.JMException Cleanup failed for JMX-related reasons.
 */
public void cleanup() throws IOException, JMException {
    try {
        ((NotificationEmitter)proxy).
                removeNotificationListener(listener,null,null);
    } finally {
        ManagementFactory.getPlatformMBeanServer().
            unregisterMBean(ScanManager.SCAN_MANAGER_NAME);
    }
}