下面列出了怎么用javax.management.NotificationEmitter的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* 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;
}
/**
* 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;
}
/**
* 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;
}
/**
* 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;
}
/**
* Register to all notifications from the GC MXBeans.
* @param listener A java NotificationListener
*/
public static void registerGCListener(GCListener listener) {
// takes the GC listener and makes javax NotificationListener that filters GC notifications
NotificationListener notificationListener = new NotificationListener() {
@Override
public void handleNotification(Notification notification, Object handback) {
if (!notification.getType().equals(GarbageCollectionNotificationInfo.GARBAGE_COLLECTION_NOTIFICATION)) return;
// get the GC info object
GarbageCollectionNotificationInfo info = GarbageCollectionNotificationInfo.from((CompositeData)notification.getUserData());
String gcAction = info.getGcAction();
if (MINOR_GC_ACTION.equals(gcAction)) {
listener.onMinorGc(info.getGcInfo().getDuration());
}
else if (MAJOR_GC_ACTION.equals(gcAction)) {
listener.onMajorGc(info.getGcInfo().getDuration());
}
}
};
// register to the GC beans
for (GarbageCollectorMXBean bean: ManagementFactory.getGarbageCollectorMXBeans()) {
((NotificationEmitter)bean).addNotificationListener(notificationListener, null, null);
}
}
/**
* emitters are used to listen to each memory pool (usually young / old gen). This function sets up the emitters
* if not already
*/
private synchronized void setupEmitters() {
if(emitters == null) {
emitters = new ArrayList<>();
// garbage collector for old and young gen
List<GarbageCollectorMXBean> garbageCollectorBeans = java.lang.management.ManagementFactory.getGarbageCollectorMXBeans();
logger.finest("Setting up listeners for garbage collection ");
for (GarbageCollectorMXBean garbageCollectorBean : garbageCollectorBeans) {
// to log
// listen to notification from the emitter
NotificationEmitter emitter = (NotificationEmitter) garbageCollectorBean;
emitters.add(emitter);
emitter.addNotificationListener(listener, null, null);
}
}
}
public static void preInit(Config config) {
((Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME)).setLevel(
Level.valueOf(config.getString("log-level").toUpperCase())
);
if(config.getBoolean("prometheus.enabled")) {
PrometheusUtils.setup();
var listener = new GCListener();
for(var gcBean : ManagementFactory.getGarbageCollectorMXBeans()) {
if(gcBean instanceof NotificationEmitter) {
((NotificationEmitter) gcBean)
.addNotificationListener(listener, null, gcBean);
}
}
}
if(config.getBoolean("sentry.enabled")) {
SentryUtils.setup(config);
}
}
/**
* 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;
}
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());
}
public PrometheusMetrics() {
InstrumentedAppender prometheusAppender = new InstrumentedAppender();
//log metrics
final LoggerContext factory = (LoggerContext) LoggerFactory.getILoggerFactory();
final ch.qos.logback.classic.Logger root = factory.getLogger(Logger.ROOT_LOGGER_NAME);
prometheusAppender.setContext(root.getLoggerContext());
prometheusAppender.start();
root.addAppender(prometheusAppender);
//jvm (hotspot) metrics
DefaultExports.initialize();
//gc pause buckets
final GcNotificationListener gcNotificationListener = new GcNotificationListener();
for (GarbageCollectorMXBean gcBean : ManagementFactory.getGarbageCollectorMXBeans()) {
if (gcBean instanceof NotificationEmitter) {
((NotificationEmitter) gcBean).addNotificationListener(gcNotificationListener, null, gcBean);
}
}
log.info("Prometheus metrics set up");
}
private void registerForNotifications() {
// Register the listener with MemoryMXBean
NotificationEmitter emitter = (NotificationEmitter) ManagementFactory.getMemoryMXBean();
emitter.addNotificationListener(listener, null, null);
// set collection usage threshold.
for (MemoryPoolMXBean pool : ManagementFactory.getMemoryPoolMXBeans()) {
if (pool.getType() == MemoryType.HEAP &&
pool.isUsageThresholdSupported() &&
pool.isCollectionUsageThresholdSupported()) {
long threshold = (pool.getUsage().getMax() * thresholdPercentage) / 100;
logger.info("setting collection threshold for " + pool.getName() +
" with max " + pool.getUsage().getMax() +
" to " + threshold);
pool.setCollectionUsageThreshold(threshold);
monitoredPools.put(pool.getName(), pool.getCollectionUsageThresholdCount());
} else {
logger.info("skip monitoring for pool " + pool.getName());
}
}
}
/**
* 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;
}
/**
* 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;
}
/**
* 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);
}
/**
* 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);
}
}
public void removeNotificationListener(
ObjectName name, NotificationListener listener,
NotificationFilter filter, Object handback)
throws InstanceNotFoundException, ListenerNotFoundException {
NotificationEmitter userMBean =
(NotificationEmitter) getMBean(name);
NotificationListener wrappedListener =
wrappedListener(name, userMBean, listener);
userMBean.removeNotificationListener(wrappedListener, filter, handback);
}
/**
* 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);
}
/**
* 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);
}
}
/**
* Uninstalls any attached GC listeners.
*
* @see #start()
*/
public void stop() {
for (Map.Entry<NotificationEmitter, NotificationListener> entry : gcListenerMap.entrySet()) {
try {
entry.getKey().removeNotificationListener(entry.getValue());
} catch (ListenerNotFoundException e) {
// should never happen, ignore
}
}
}
public void removeNotificationListener(
ObjectName name, NotificationListener listener,
NotificationFilter filter, Object handback)
throws InstanceNotFoundException, ListenerNotFoundException {
NotificationEmitter userMBean =
(NotificationEmitter) getMBean(name);
NotificationListener wrappedListener =
wrappedListener(name, userMBean, listener);
userMBean.removeNotificationListener(wrappedListener, filter, handback);
}
/**
* add listener to gc Garbage collector gc event
**/
@Override
public void addGCEventListener(NotificationListener listener){
List<GarbageCollectorMXBean> gcbeans = ManagementFactory.getGarbageCollectorMXBeans();
for (GarbageCollectorMXBean gcbean : gcbeans) {
NotificationEmitter emitter = (NotificationEmitter) gcbean;
emitter.addNotificationListener(listener, null, null);
}
}
public void unsubscribe() {
for (GarbageCollectorMXBean bean : ManagementFactory.getGarbageCollectorMXBeans()) {
NotificationEmitter emitter = (NotificationEmitter) bean;
try {
emitter.removeNotificationListener(listener);
} catch (ListenerNotFoundException e) {
LOGGER.debug("Error during unsuscribing GC listener", e);
}
}
}
private void startListening() {
val notificationListener = new GcNotificationListener();
for (GarbageCollectorMXBean mbean : ManagementFactory.getGarbageCollectorMXBeans()) {
if (mbean instanceof NotificationEmitter) {
val emitter = (NotificationEmitter) mbean;
emitter.addNotificationListener(notificationListener, null, null);
}
}
}
/**
* 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);
}
}
public void removeNotificationListener(
ObjectName name, NotificationListener listener,
NotificationFilter filter, Object handback)
throws InstanceNotFoundException, ListenerNotFoundException {
NotificationEmitter userMBean =
(NotificationEmitter) getMBean(name);
NotificationListener wrappedListener =
wrappedListener(name, userMBean, listener);
userMBean.removeNotificationListener(wrappedListener, filter, handback);
}
public GarbageCollectionMonitor() {
List<GarbageCollectorMXBean> beans = ManagementFactory.getGarbageCollectorMXBeans();
for (GarbageCollectorMXBean bean : beans) {
if (!(bean instanceof NotificationEmitter)) {
continue;
}
NotificationEmitter notificationEmitter = (NotificationEmitter) bean;
notificationEmitter.addNotificationListener(this, null, null);
this.emitters.add(notificationEmitter);
}
}
/**
* tear down emitters
*/
private synchronized void tearDownEmitters() {
if(emitters != null) {
logger.finest("tearing down listeners for garbage collection");
for(NotificationEmitter emitter : emitters) {
try {
emitter.removeNotificationListener(listener);
} catch (ListenerNotFoundException e) {
throw new IllegalStateException("already removed somehow...");
}
}
}
}
/**
* 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);
}
/**
* 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);
}
}
/**
* 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;
}
}