VirtualMachineTracer.java 文件源码

java
阅读 19 收藏 0 点赞 0 评论 0

项目:dsl-devkit 作者:
/**
 * 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);
  }
}
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号