Java Code Examples for java.lang.management.GarbageCollectorMXBean

The following are top voted examples for showing how to use java.lang.management.GarbageCollectorMXBean. 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: Reer   File: GarbageCollectionCheck.java   Source Code and License 6 votes vote down vote up
@Override
public void run() {
    List<GarbageCollectorMXBean> garbageCollectorMXBeans = ManagementFactory.getGarbageCollectorMXBeans();
    GarbageCollectorMXBean garbageCollectorMXBean = CollectionUtils.findFirst(garbageCollectorMXBeans, new Spec<GarbageCollectorMXBean>() {
        @Override
        public boolean isSatisfiedBy(GarbageCollectorMXBean mbean) {
            return mbean.getName().equals(garbageCollector);
        }
    });

    List<MemoryPoolMXBean> memoryPoolMXBeans = ManagementFactory.getMemoryPoolMXBeans();
    for (MemoryPoolMXBean memoryPoolMXBean : memoryPoolMXBeans) {
        String pool = memoryPoolMXBean.getName();
        if (memoryPools.contains(pool)) {
            GarbageCollectionEvent event = new GarbageCollectionEvent(System.currentTimeMillis(), memoryPoolMXBean.getCollectionUsage(), garbageCollectorMXBean.getCollectionCount());
            events.get(pool).slideAndInsert(event);
        }
    }
}
 
Example 2
Project: swage   File: GarbageCollectorSensor.java   Source Code and License 6 votes vote down vote up
@Override
public void sense(final MetricRecorder.Context metricContext)
{
    List<GarbageCollectorMXBean> gcBeans = ManagementFactory.getGarbageCollectorMXBeans();

    // sum up metrics for all the garbage collectors
    //TODO: individual metrics per gc?
    long totalCollections = 0L;
    long totalTime = 0L;
    for (GarbageCollectorMXBean mxBean : gcBeans) {
        totalCollections += mxBean.getCollectionCount();
        totalTime += mxBean.getCollectionTime();
    }

    metricContext.record(COLLECTION_COUNT_TOTAL, totalCollections, Unit.NONE);
    metricContext.record(COLLECTION_TIME_TOTAL, totalTime, Unit.MILLISECOND);

    metricContext.record(COLLECTION_COUNT, (totalCollections - prevTotalCollections), Unit.NONE);
    metricContext.record(COLLECTION_TIME, (totalTime - prevTotalTime), Unit.MILLISECOND);

    prevTotalCollections = totalCollections;
    prevTotalTime = totalTime;
}
 
Example 3
Project: hadoop-oss   File: JvmMetrics.java   Source Code and License 6 votes vote down vote up
private void getGcUsage(MetricsRecordBuilder rb) {
  long count = 0;
  long timeMillis = 0;
  for (GarbageCollectorMXBean gcBean : gcBeans) {
    long c = gcBean.getCollectionCount();
    long t = gcBean.getCollectionTime();
    MetricsInfo[] gcInfo = getGcInfo(gcBean.getName());
    rb.addCounter(gcInfo[0], c).addCounter(gcInfo[1], t);
    count += c;
    timeMillis += t;
  }
  rb.addCounter(GcCount, count)
    .addCounter(GcTimeMillis, timeMillis);
  
  if (pauseMonitor != null) {
    rb.addCounter(GcNumWarnThresholdExceeded,
        pauseMonitor.getNumGcWarnThresholdExceeded());
    rb.addCounter(GcNumInfoThresholdExceeded,
        pauseMonitor.getNumGcInfoThresholdExceeded());
    rb.addCounter(GcTotalExtraSleepTime,
        pauseMonitor.getTotalGcExtraSleepTime());
  }
}
 
Example 4
Project: cljbuck   File: Main.java   Source Code and License 6 votes vote down vote up
public static void printGCStats() {
    long totalGarbageCollections = 0;
    long garbageCollectionTime = 0;

    for (GarbageCollectorMXBean gc : ManagementFactory.getGarbageCollectorMXBeans()) {

        long count = gc.getCollectionCount();

        if (count >= 0) {
            totalGarbageCollections += count;
        }

        long time = gc.getCollectionTime();

        if (time >= 0) {
            garbageCollectionTime += time;
        }
    }

    System.out.println("Total Garbage Collections: " + totalGarbageCollections);
    System.out.println("Total Garbage Collection Time (ms): " + garbageCollectionTime);
}
 
Example 5
Project: cljbuck   File: Main.java   Source Code and License 6 votes vote down vote up
public static void printGCStats(Tracer logger) {
    long totalGarbageCollections = 0;
    long garbageCollectionTime = 0;

    for (GarbageCollectorMXBean gc : ManagementFactory.getGarbageCollectorMXBeans()) {

        long count = gc.getCollectionCount();

        if (count >= 0) {
            totalGarbageCollections += count;
        }

        long time = gc.getCollectionTime();

        if (time >= 0) {
            garbageCollectionTime += time;
        }
    }

    logger.info("Total Garbage Collections: " + totalGarbageCollections);
    logger.info("Total Garbage Collection Time (ms): " + garbageCollectionTime);
}
 
Example 6
Project: otus_java_2017_06   File: Main.java   Source Code and License 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 7
Project: OpenJSharp   File: GcInfoBuilder.java   Source Code and License 6 votes vote down vote up
GcInfoBuilder(GarbageCollectorMXBean gc, String[] poolNames) {
    this.gc = gc;
    this.poolNames = poolNames;
    this.gcExtItemCount = getNumGcExtAttributes(gc);
    this.gcExtItemNames = new String[gcExtItemCount];
    this.gcExtItemDescs = new String[gcExtItemCount];
    this.gcExtItemTypes = new char[gcExtItemCount];

    // Fill the information about extension attributes
    fillGcAttributeInfo(gc, gcExtItemCount, gcExtItemNames,
                        gcExtItemTypes, gcExtItemDescs);

    // lazily build the CompositeType for the GcInfo
    // including the GC-specific extension attributes
    this.gcInfoCompositeType = null;
}
 
Example 8
Project: OpenJSharp   File: JvmMemGCTableMetaImpl.java   Source Code and License 6 votes vote down vote up
/**
 * Returns the index that immediately follows the given
 * <var>index</var>. The returned index is strictly greater
 * than the given <var>index</var>, and is contained in the table.
 * <br>If the given <var>index</var> is null, returns the first
 * index in the table.
 * <br>If there are no index after the given <var>index</var>,
 * returns null.
 **/
public SnmpOid getNext(SnmpTableHandler handler, SnmpOid index) {

    // try to call the optimized method
    if (handler instanceof SnmpCachedData)
        return getNext((SnmpCachedData)handler, index);

    // too bad - revert to non-optimized generic algorithm
    SnmpOid next = index;
    do {
        next = handler.getNext(next);
        final Object value = handler.getData(next);
        if (value instanceof GarbageCollectorMXBean)
            // That's the next! return it
            return next;
        // skip to next index...
    } while (next != null);
    return null;
}
 
Example 9
Project: otus_java_2017_04   File: Main.java   Source Code and License 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 10
Project: hadoop   File: JvmMetrics.java   Source Code and License 6 votes vote down vote up
private void getGcUsage(MetricsRecordBuilder rb) {
  long count = 0;
  long timeMillis = 0;
  for (GarbageCollectorMXBean gcBean : gcBeans) {
    long c = gcBean.getCollectionCount();
    long t = gcBean.getCollectionTime();
    MetricsInfo[] gcInfo = getGcInfo(gcBean.getName());
    rb.addCounter(gcInfo[0], c).addCounter(gcInfo[1], t);
    count += c;
    timeMillis += t;
  }
  rb.addCounter(GcCount, count)
    .addCounter(GcTimeMillis, timeMillis);
  
  if (pauseMonitor != null) {
    rb.addCounter(GcNumWarnThresholdExceeded,
        pauseMonitor.getNumGcWarnThreadholdExceeded());
    rb.addCounter(GcNumInfoThresholdExceeded,
        pauseMonitor.getNumGcInfoThresholdExceeded());
    rb.addCounter(GcTotalExtraSleepTime,
        pauseMonitor.getTotalGcExtraSleepTime());
  }
}
 
Example 11
Project: jdk8u-jdk   File: GcInfoBuilder.java   Source Code and License 6 votes vote down vote up
GcInfoBuilder(GarbageCollectorMXBean gc, String[] poolNames) {
    this.gc = gc;
    this.poolNames = poolNames;
    this.gcExtItemCount = getNumGcExtAttributes(gc);
    this.gcExtItemNames = new String[gcExtItemCount];
    this.gcExtItemDescs = new String[gcExtItemCount];
    this.gcExtItemTypes = new char[gcExtItemCount];

    // Fill the information about extension attributes
    fillGcAttributeInfo(gc, gcExtItemCount, gcExtItemNames,
                        gcExtItemTypes, gcExtItemDescs);

    // lazily build the CompositeType for the GcInfo
    // including the GC-specific extension attributes
    this.gcInfoCompositeType = null;
}
 
Example 12
Project: jdk8u-jdk   File: JvmMemGCTableMetaImpl.java   Source Code and License 6 votes vote down vote up
/**
 * Returns the index that immediately follows the given
 * <var>index</var>. The returned index is strictly greater
 * than the given <var>index</var>, and is contained in the table.
 * <br>If the given <var>index</var> is null, returns the first
 * index in the table.
 * <br>If there are no index after the given <var>index</var>,
 * returns null.
 **/
public SnmpOid getNext(SnmpTableHandler handler, SnmpOid index) {

    // try to call the optimized method
    if (handler instanceof SnmpCachedData)
        return getNext((SnmpCachedData)handler, index);

    // too bad - revert to non-optimized generic algorithm
    SnmpOid next = index;
    do {
        next = handler.getNext(next);
        final Object value = handler.getData(next);
        if (value instanceof GarbageCollectorMXBean)
            // That's the next! return it
            return next;
        // skip to next index...
    } while (next != null);
    return null;
}
 
Example 13
Project: uavstack   File: JVMToolHelper.java   Source Code and License 6 votes vote down vote up
public static Map<String, Long> readGCUsage(List<GarbageCollectorMXBean> gcmbList) {

        Map<String, Long> m = new LinkedHashMap<String, Long>();

        for (GarbageCollectorMXBean gcmb : gcmbList) {

            String name = gcmb.getName();
            String gcName = null;
            if (minorGC.contains(name)) {
                gcName = "mgc";

            }
            else if (fullGC.contains(name)) {
                gcName = "fgc";
            }

            if (gcName == null) {
                continue;
            }

            m.put(gcName + "_count", gcmb.getCollectionCount());
            m.put(gcName + "_time", gcmb.getCollectionTime());
        }

        return m;
    }
 
Example 14
Project: uavstack   File: JVMStateCapHandler.java   Source Code and License 6 votes vote down vote up
private void readGCUsage(MonitorElementInstance instance) {

        List<GarbageCollectorMXBean> gcmbList = ManagementFactory.getGarbageCollectorMXBeans();

        for (GarbageCollectorMXBean gcmb : gcmbList) {

            String name = gcmb.getName();
            String gcName = null;
            if (minorGC.contains(name)) {
                gcName = "mgc";

            }
            else if (fullGC.contains(name)) {
                gcName = "fgc";
            }

            if (gcName == null) {
                continue;
            }

            instance.setValue(gcName + "_count", gcmb.getCollectionCount());
            instance.setValue(gcName + "_time", gcmb.getCollectionTime());
        }
    }
 
Example 15
Project: openjdk-jdk10   File: TestCMSClassUnloadingEnabledHWM.java   Source Code and License 6 votes vote down vote up
public static void main(String [] args) throws Exception {
  if (args.length != 1) {
    throw new IllegalArgumentException("Usage: <MetaspaceSize>");
  }

  WhiteBox wb = WhiteBox.getWhiteBox();

  // Allocate past the MetaspaceSize limit.
  long metaspaceSize = Long.parseLong(args[0]);
  long allocationBeyondMetaspaceSize  = metaspaceSize * 2;
  long metaspace = wb.allocateMetaspace(null, allocationBeyondMetaspaceSize);

  // Wait for at least one GC to occur. The caller will parse the log files produced.
  GarbageCollectorMXBean cmsGCBean = getCMSGCBean();
  while (cmsGCBean.getCollectionCount() == 0) {
    Thread.sleep(100);
  }

  wb.freeMetaspace(null, metaspace, metaspace);
}
 
Example 16
Project: openjdk-jdk10   File: TestTargetSurvivorRatioFlag.java   Source Code and License 6 votes vote down vote up
/**
 * Allocate (<b>ratio</b> * <b>maxSize</b> / 100) bytes of objects
 * and force at least "MaxTenuringThreshold" minor GCs.
 *
 * @param ratio ratio used to calculate how many objects should be allocated
 * @param maxSize estimated max survivor space size
 */
public static void allocateMemory(double ratio, long maxSize) throws Exception {
    GarbageCollectorMXBean youngGCBean = GCTypes.YoungGCType.getYoungGCBean();
    long garbageSize = (long) (maxSize * (ratio / 100.0));
    int arrayLength = (int) (garbageSize / CHUNK_SIZE);
    AllocationHelper allocator = new AllocationHelper(1, arrayLength, ARRAY_LENGTH, null);

    System.out.println(START_TEST);
    System.gc();
    final long initialGcId = youngGCBean.getCollectionCount();
    // allocate memory
    allocator.allocateMemoryAndVerify();

    // force minor GC
    while (youngGCBean.getCollectionCount() <= initialGcId + MAX_TENURING_THRESHOLD * 2) {
        byte b[] = new byte[ARRAY_LENGTH];
    }

    allocator.release();
    System.out.println(END_TEST);
}
 
Example 17
Project: openjdk-jdk10   File: JstatGcCapacityResults.java   Source Code and License 6 votes vote down vote up
/**
 * Check if the tenured generation are currently using a parallel GC.
 */
protected static boolean isTenuredParallelGC() {
    // Currently the only parallel GC for the tenured generation is PS MarkSweep.
    List<String> parallelGCs = Arrays.asList(new String[] { "PS MarkSweep"});
    try {
        List<GarbageCollectorMXBean> beans = ManagementFactory.getGarbageCollectorMXBeans();
        for (GarbageCollectorMXBean bean : beans) {
            if (parallelGCs.contains(bean.getName())) {
                return true;
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return false;
}
 
Example 18
Project: openjdk-jdk10   File: GcInfoBuilder.java   Source Code and License 6 votes vote down vote up
GcInfoBuilder(GarbageCollectorMXBean gc, String[] poolNames) {
    this.gc = gc;
    this.poolNames = poolNames;
    this.gcExtItemCount = getNumGcExtAttributes(gc);
    this.gcExtItemNames = new String[gcExtItemCount];
    this.gcExtItemDescs = new String[gcExtItemCount];
    this.gcExtItemTypes = new char[gcExtItemCount];

    // Fill the information about extension attributes
    fillGcAttributeInfo(gc, gcExtItemCount, gcExtItemNames,
                        gcExtItemTypes, gcExtItemDescs);

    // lazily build the CompositeType for the GcInfo
    // including the GC-specific extension attributes
    this.gcInfoCompositeType = null;
}
 
Example 19
Project: ditb   File: Utils.java   Source Code and License 6 votes vote down vote up
/**
 * Returns a map of garbage collectors and their stats.
 * The first object in the array is the total count since JVM start and the
 * second is the total time (ms) since JVM start.
 * If a garbage collectors does not support the collector MXBean, then it
 * will not be represented in the map.
 * @return A non-null map of garbage collectors and their metrics. The map
 * may be empty.
 */
public static Map<String, Long[]> getGCStatst() {
  final List<GarbageCollectorMXBean> gcBeans =
      ManagementFactory.getGarbageCollectorMXBeans();
  final Map<String, Long[]> map = new HashMap<String, Long[]>(gcBeans.size());
  for (final GarbageCollectorMXBean bean : gcBeans) {
    if (!bean.isValid() || bean.getCollectionCount() < 0 ||
        bean.getCollectionTime() < 0) {
      continue;
    }

    final Long[] measurements = new Long[]{
        bean.getCollectionCount(),
        bean.getCollectionTime()
    };
    map.put(bean.getName().replace(" ", "_"), measurements);
  }
  return map;
}
 
Example 20
Project: openjdk9   File: TestCMSClassUnloadingEnabledHWM.java   Source Code and License 6 votes vote down vote up
public static void main(String [] args) throws Exception {
  if (args.length != 1) {
    throw new IllegalArgumentException("Usage: <MetaspaceSize>");
  }

  WhiteBox wb = WhiteBox.getWhiteBox();

  // Allocate past the MetaspaceSize limit.
  long metaspaceSize = Long.parseLong(args[0]);
  long allocationBeyondMetaspaceSize  = metaspaceSize * 2;
  long metaspace = wb.allocateMetaspace(null, allocationBeyondMetaspaceSize);

  // Wait for at least one GC to occur. The caller will parse the log files produced.
  GarbageCollectorMXBean cmsGCBean = getCMSGCBean();
  while (cmsGCBean.getCollectionCount() == 0) {
    Thread.sleep(100);
  }

  wb.freeMetaspace(null, metaspace, metaspace);
}
 
Example 21
Project: openjdk9   File: TestTargetSurvivorRatioFlag.java   Source Code and License 6 votes vote down vote up
/**
 * Allocate (<b>ratio</b> * <b>maxSize</b> / 100) bytes of objects
 * and force at least "MaxTenuringThreshold" minor GCs.
 *
 * @param ratio ratio used to calculate how many objects should be allocated
 * @param maxSize estimated max survivor space size
 */
public static void allocateMemory(double ratio, long maxSize) throws Exception {
    GarbageCollectorMXBean youngGCBean = GCTypes.YoungGCType.getYoungGCBean();
    long garbageSize = (long) (maxSize * (ratio / 100.0));
    int arrayLength = (int) (garbageSize / CHUNK_SIZE);
    AllocationHelper allocator = new AllocationHelper(1, arrayLength, ARRAY_LENGTH, null);

    System.out.println(START_TEST);
    System.gc();
    final long initialGcId = youngGCBean.getCollectionCount();
    // allocate memory
    allocator.allocateMemoryAndVerify();

    // force minor GC
    while (youngGCBean.getCollectionCount() <= initialGcId + MAX_TENURING_THRESHOLD * 2) {
        byte b[] = new byte[ARRAY_LENGTH];
    }

    allocator.release();
    System.out.println(END_TEST);
}
 
Example 22
Project: flink   File: MetricUtils.java   Source Code and License 6 votes vote down vote up
private static void instantiateGarbageCollectorMetrics(MetricGroup metrics) {
	List<GarbageCollectorMXBean> garbageCollectors = ManagementFactory.getGarbageCollectorMXBeans();

	for (final GarbageCollectorMXBean garbageCollector: garbageCollectors) {
		MetricGroup gcGroup = metrics.addGroup(garbageCollector.getName());

		gcGroup.<Long, Gauge<Long>>gauge("Count", new Gauge<Long> () {
			@Override
			public Long getValue() {
				return garbageCollector.getCollectionCount();
			}
		});

		gcGroup.<Long, Gauge<Long>>gauge("Time", new Gauge<Long> () {
			@Override
			public Long getValue() {
				return garbageCollector.getCollectionTime();
			}
		});
	}
}
 
Example 23
Project: flink   File: TaskExecutorMetricsInitializer.java   Source Code and License 6 votes vote down vote up
private static void instantiateGarbageCollectorMetrics(MetricGroup metrics) {
	List<GarbageCollectorMXBean> garbageCollectors = ManagementFactory.getGarbageCollectorMXBeans();

	for (final GarbageCollectorMXBean garbageCollector: garbageCollectors) {
		MetricGroup gcGroup = metrics.addGroup(garbageCollector.getName());

		gcGroup.<Long, Gauge<Long>>gauge("Count", new Gauge<Long> () {
			@Override
			public Long getValue() {
				return garbageCollector.getCollectionCount();
			}
		});

		gcGroup.<Long, Gauge<Long>>gauge("Time", new Gauge<Long> () {
			@Override
			public Long getValue() {
				return garbageCollector.getCollectionTime();
			}
		});
	}
}
 
Example 24
Project: linden   File: RuntimeInfoUtils.java   Source Code and License 6 votes vote down vote up
public static JVMInfo getJVMInfo() {
  JVMInfo jvmInfo = new JVMInfo();

  Runtime runtime = Runtime.getRuntime();
  jvmInfo.setFreeMemory(runtime.freeMemory());
  jvmInfo.setTotalMemory(runtime.totalMemory());
  jvmInfo.setMaxMemory(runtime.maxMemory());

  int gcCount = 0;
  long gcTime = 0;
  for (GarbageCollectorMXBean gc : ManagementFactory.getGarbageCollectorMXBeans()) {
    long count = gc.getCollectionCount();
    if (count >= 0) {
      gcCount += count;
    }
    long time = gc.getCollectionTime();
    if (time >= 0) {
      gcTime += time;
    }
  }
  jvmInfo.setGcCount(gcCount);
  jvmInfo.setGcTime(gcTime);
  List<String> args = ManagementFactory.getRuntimeMXBean().getInputArguments();
  jvmInfo.setArguments(joiner.join(args));
  return jvmInfo;
}
 
Example 25
Project: flink   File: MemoryLogger.java   Source Code and License 6 votes vote down vote up
/**
 * Gets the garbage collection statistics from the JVM.
 *
 * @param gcMXBeans The collection of garbage collector beans.
 * @return A string denoting the number of times and total elapsed time in garbage collection.
 */
public static String getGarbageCollectorStatsAsString(List<GarbageCollectorMXBean> gcMXBeans) {
	StringBuilder bld = new StringBuilder("Garbage collector stats: ");
	
	for (GarbageCollectorMXBean bean : gcMXBeans) {
		bld.append('[').append(bean.getName()).append(", GC TIME (ms): ").append(bean.getCollectionTime());
		bld.append(", GC COUNT: ").append(bean.getCollectionCount()).append(']');
		
		bld.append(", ");
	}
	
	if (!gcMXBeans.isEmpty()) {
		bld.setLength(bld.length() - 2);
	}
	
	return bld.toString();
}
 
Example 26
Project: tracing-framework   File: XTraceGCUtils.java   Source Code and License 6 votes vote down vote up
@Override
public void handleNotification(Notification notification, Object handback) {
    try {
        // Make sure it's the right notification type
        if (!notification.getType().equals(GarbageCollectionNotificationInfo.GARBAGE_COLLECTION_NOTIFICATION))
            return;

        // Extract the GcInfo as appropriate, working around the OpenJDK
        // GcInfo cycles/milliseconds bug
        GarbageCollectorMXBean bean = (GarbageCollectorMXBean) handback;
        GarbageCollectionNotificationInfo info = getInfo(notification);
        GcInfo gc = getGcInfo(info, bean);

        // Call the callback
        this.callback.onGC(gc);
    } catch (Exception e) {
        // swallow
    }
}
 
Example 27
Project: intellij-ce-playground   File: ProcessRecorderFactory.java   Source Code and License 6 votes vote down vote up
public static void shutdown() throws InterruptedException {
    synchronized (LOCK) {
        List<GarbageCollectorMXBean> garbageCollectorMXBeans = ManagementFactory
                .getGarbageCollectorMXBeans();
        ThreadRecorder.get().record(ExecutionType.FINAL_METADATA, Recorder.EmptyBlock,
                new Recorder.Property("build_time",
                        Long.toString(System.currentTimeMillis() - sINSTANCE.startTime)),
                new Recorder.Property("gc_count",
                        Long.toString(garbageCollectorMXBeans.get(0).getCollectionCount()
                                - sINSTANCE.gcCountAtStart)),
                new Recorder.Property("gc_time",
                        Long.toString(garbageCollectorMXBeans.get(0).getCollectionTime()
                                - sINSTANCE.gcTimeAtStart)));
        if (sINSTANCE.isInitialized()) {
            sINSTANCE.get().finish();
            sINSTANCE.uploadData();
        }
        sINSTANCE.processRecorder = null;
    }
}
 
Example 28
Project: bender   File: BaseHandler.java   Source Code and License 6 votes vote down vote up
private void getGCStats() {
  long currentGcCount = 0;
  long currentGcDuration = 0;

  for (GarbageCollectorMXBean gc : ManagementFactory.getGarbageCollectorMXBeans()) {
    long count = gc.getCollectionCount();

    if (count >= 0) {
      currentGcCount += count;
    }

    long time = gc.getCollectionTime();

    if (time >= 0) {
      currentGcDuration += time;
    }
  }

  logger.trace("number of GCs: " + (currentGcCount - lastGcCount) + " and time spent in GCs: "
      + (currentGcDuration - lastGcDuration) + "ms");

  lastGcCount = currentGcCount;
  lastGcDuration = currentGcDuration;
}
 
Example 29
Project: javify   File: TestGarbageCollector.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args)
{
  Iterator beans = ManagementFactory.getGarbageCollectorMXBeans().iterator();
  while (beans.hasNext())
    {
      GarbageCollectorMXBean bean = (GarbageCollectorMXBean) beans.next();
      System.out.println("Bean: " + bean);
      System.out.println("Name: " + bean.getName());
      System.out.println("Memory pool names: "
                         + Arrays.toString(bean.getMemoryPoolNames()));
      System.out.println("Is valid: "
                         + (bean.isValid() ? "yes" : "no"));
      System.out.println("Collection count: "
                         + bean.getCollectionCount());
      System.out.println("Collection time: "
                         + bean.getCollectionTime() + "ms");
    }
}
 
Example 30
Project: jdk8u_jdk   File: GcInfoBuilder.java   Source Code and License 6 votes vote down vote up
GcInfoBuilder(GarbageCollectorMXBean gc, String[] poolNames) {
    this.gc = gc;
    this.poolNames = poolNames;
    this.gcExtItemCount = getNumGcExtAttributes(gc);
    this.gcExtItemNames = new String[gcExtItemCount];
    this.gcExtItemDescs = new String[gcExtItemCount];
    this.gcExtItemTypes = new char[gcExtItemCount];

    // Fill the information about extension attributes
    fillGcAttributeInfo(gc, gcExtItemCount, gcExtItemNames,
                        gcExtItemTypes, gcExtItemDescs);

    // lazily build the CompositeType for the GcInfo
    // including the GC-specific extension attributes
    this.gcInfoCompositeType = null;
}
 
Example 31
Project: jdk8u_jdk   File: JvmMemGCTableMetaImpl.java   Source Code and License 6 votes vote down vote up
/**
 * Returns the index that immediately follows the given
 * <var>index</var>. The returned index is strictly greater
 * than the given <var>index</var>, and is contained in the table.
 * <br>If the given <var>index</var> is null, returns the first
 * index in the table.
 * <br>If there are no index after the given <var>index</var>,
 * returns null.
 **/
public SnmpOid getNext(SnmpTableHandler handler, SnmpOid index) {

    // try to call the optimized method
    if (handler instanceof SnmpCachedData)
        return getNext((SnmpCachedData)handler, index);

    // too bad - revert to non-optimized generic algorithm
    SnmpOid next = index;
    do {
        next = handler.getNext(next);
        final Object value = handler.getData(next);
        if (value instanceof GarbageCollectorMXBean)
            // That's the next! return it
            return next;
        // skip to next index...
    } while (next != null);
    return null;
}
 
Example 32
Project: emodb   File: EmoGarbageCollectorMetricSet.java   Source Code and License 6 votes vote down vote up
@Override
public Map<String, Metric> getMetrics() {
    final Map<String, Metric> metrics = new HashMap();
    for (final GarbageCollectorMXBean garbageCollectorMXBean : _garbageCollectorMXBeans) {
        final String collectorName = garbageCollectorMXBean.getName().replaceAll("[\\s]+", "_");
        String timeName = String.format("time[collector:%s]", collectorName);
        metrics.put(timeName, new Gauge<Long>() {
            @Override
            public Long getValue() {
                return garbageCollectorMXBean.getCollectionTime();
            }
        });

        String runsName = String.format("runs[collector:%s]", collectorName);
        metrics.put(runsName, new Gauge<Long>() {
            @Override
            public Long getValue() {
                return garbageCollectorMXBean.getCollectionCount();
            }
        });
    }
    return metrics;
}
 
Example 33
Project: lookaside_java-1.8.0-openjdk   File: TestCMSClassUnloadingEnabledHWM.java   Source Code and License 6 votes vote down vote up
public static void main(String [] args) throws Exception {
  if (args.length != 1) {
    throw new IllegalArgumentException("Usage: <MetaspaceSize>");
  }

  WhiteBox wb = WhiteBox.getWhiteBox();

  // Allocate past the MetaspaceSize limit.
  long metaspaceSize = Long.parseLong(args[0]);
  long allocationBeyondMetaspaceSize  = metaspaceSize * 2;
  long metaspace = wb.allocateMetaspace(null, allocationBeyondMetaspaceSize);

  // Wait for at least one GC to occur. The caller will parse the log files produced.
  GarbageCollectorMXBean cmsGCBean = getCMSGCBean();
  while (cmsGCBean.getCollectionCount() == 0) {
    Thread.sleep(100);
  }

  wb.freeMetaspace(null, metaspace, metaspace);
}
 
Example 34
Project: lookaside_java-1.8.0-openjdk   File: GcInfoBuilder.java   Source Code and License 6 votes vote down vote up
GcInfoBuilder(GarbageCollectorMXBean gc, String[] poolNames) {
    this.gc = gc;
    this.poolNames = poolNames;
    this.gcExtItemCount = getNumGcExtAttributes(gc);
    this.gcExtItemNames = new String[gcExtItemCount];
    this.gcExtItemDescs = new String[gcExtItemCount];
    this.gcExtItemTypes = new char[gcExtItemCount];

    // Fill the information about extension attributes
    fillGcAttributeInfo(gc, gcExtItemCount, gcExtItemNames,
                        gcExtItemTypes, gcExtItemDescs);

    // lazily build the CompositeType for the GcInfo
    // including the GC-specific extension attributes
    this.gcInfoCompositeType = null;
}
 
Example 35
Project: lookaside_java-1.8.0-openjdk   File: JvmMemGCTableMetaImpl.java   Source Code and License 6 votes vote down vote up
/**
 * Returns the index that immediately follows the given
 * <var>index</var>. The returned index is strictly greater
 * than the given <var>index</var>, and is contained in the table.
 * <br>If the given <var>index</var> is null, returns the first
 * index in the table.
 * <br>If there are no index after the given <var>index</var>,
 * returns null.
 **/
public SnmpOid getNext(SnmpTableHandler handler, SnmpOid index) {

    // try to call the optimized method
    if (handler instanceof SnmpCachedData)
        return getNext((SnmpCachedData)handler, index);

    // too bad - revert to non-optimized generic algorithm
    SnmpOid next = index;
    do {
        next = handler.getNext(next);
        final Object value = handler.getData(next);
        if (value instanceof GarbageCollectorMXBean)
            // That's the next! return it
            return next;
        // skip to next index...
    } while (next != null);
    return null;
}
 
Example 36
Project: intellij-ce-playground   File: LightPlatformTestCase.java   Source Code and License 6 votes vote down vote up
@SuppressWarnings("UseOfSystemOutOrSystemErr")
public static void reportTestExecutionStatistics() {
  System.out.println("----- TEST STATISTICS -----");
  UsefulTestCase.logSetupTeardownCosts();
  System.out.println(String.format("##teamcity[buildStatisticValue key='ideaTests.appInstancesCreated' value='%d']",
                                   MockApplication.INSTANCES_CREATED));
  System.out.println(String.format("##teamcity[buildStatisticValue key='ideaTests.projectInstancesCreated' value='%d']",
                                   ProjectManagerImpl.TEST_PROJECTS_CREATED));
  long totalGcTime = 0;
  for (GarbageCollectorMXBean mxBean : ManagementFactory.getGarbageCollectorMXBeans()) {
    totalGcTime += mxBean.getCollectionTime();
  }
  System.out.println(String.format("##teamcity[buildStatisticValue key='ideaTests.gcTimeMs' value='%d']", totalGcTime));
  System.out.println(String.format("##teamcity[buildStatisticValue key='ideaTests.classesLoaded' value='%d']",
                                   ManagementFactory.getClassLoadingMXBean().getTotalLoadedClassCount()));
}
 
Example 37
Project: light-task-scheduler   File: JVMGC.java   Source Code and License 6 votes vote down vote up
private JVMGC() {
    for (GarbageCollectorMXBean item : ManagementFactory.getGarbageCollectorMXBeans()) {
        if ("ConcurrentMarkSweep".equals(item.getName()) //
                || "MarkSweepCompact".equals(item.getName()) //
                || "PS MarkSweep".equals(item.getName()) //
                || "G1 Old Generation".equals(item.getName()) //
                || "Garbage collection optimized for short pausetimes Old Collector".equals(item.getName()) //
                || "Garbage collection optimized for throughput Old Collector".equals(item.getName()) //
                || "Garbage collection optimized for deterministic pausetimes Old Collector".equals(item.getName()) //
                ) {
            fullGC = item;
        } else if ("ParNew".equals(item.getName()) //
                || "Copy".equals(item.getName()) //
                || "PS Scavenge".equals(item.getName()) //
                || "G1 Young Generation".equals(item.getName()) //
                || "Garbage collection optimized for short pausetimes Young Collector".equals(item.getName()) //
                || "Garbage collection optimized for throughput Young Collector".equals(item.getName()) //
                || "Garbage collection optimized for deterministic pausetimes Young Collector".equals(item.getName()) //
                ) {
            youngGC = item;
        }
    }
}
 
Example 38
Project: gc-monitor   File: GcStatistics.java   Source Code and License 6 votes vote down vote up
public static GcStatistics create(GcMonitorConfiguration configuration) {
    SortedMap<String, MonitoredCollector> monitoredCollectors = new TreeMap<>();
    SortedMap<String, CollectorStatistics> perCollectorStatistics = new TreeMap<>();
    List<GarbageCollectorMXBean> garbageCollectorMXBeans = configuration.getGarbageCollectorMXBeans();
    long currentTimeMillis = configuration.getClock().currentTimeMillis();

    Optional<CollectorStatistics> aggregatedStatistics;
    if (garbageCollectorMXBeans.size() > 1 && configuration.isAggregateDifferentCollectors()) {
        aggregatedStatistics = Optional.of(createCollectorStatistics(configuration, currentTimeMillis));
        perCollectorStatistics.put(GcMonitorConfiguration.AGGREGATED_COLLECTOR_NAME, aggregatedStatistics.get());
    } else {
        aggregatedStatistics = Optional.empty();
    }

    for (GarbageCollectorMXBean bean : configuration.getGarbageCollectorMXBeans()) {
        CollectorStatistics collectorStatistics = createCollectorStatistics(configuration, currentTimeMillis);
        perCollectorStatistics.put(bean.getName(), collectorStatistics);
        MonitoredCollector monitoredCollector = new MonitoredCollector(bean, aggregatedStatistics, collectorStatistics);
        monitoredCollectors.put(bean.getName(), monitoredCollector);
    }
    return new GcStatistics(configuration, monitoredCollectors, perCollectorStatistics);
}
 
Example 39
Project: gc-monitor   File: GcMonitorBuilder.java   Source Code and License 6 votes vote down vote up
private void checkMbeans(Collection<GarbageCollectorMXBean> garbageCollectorMXBeans) {
    if (garbageCollectorMXBeans == null) {
        throw new IllegalArgumentException("garbageCollectorMXBeans should not be null");
    }
    if (garbageCollectorMXBeans.isEmpty()) {
        throw new IllegalArgumentException("garbageCollectorMXBeans should not be empty");
    }
    Set<String> names = new HashSet<>();
    for (GarbageCollectorMXBean bean : garbageCollectorMXBeans) {
        if (bean == null) {
            throw new IllegalArgumentException("garbageCollectorMXBeans should not contain null elements");
        }
        String name = bean.getName();
        if (names.contains(name)) {
            throw new IllegalArgumentException("garbageCollectorMXBeans contains two collectors with name [" + name + "]");
        }
        names.add(name);
    }
}
 
Example 40
Project: Reer   File: GarbageCollectionInfo.java   Source Code and License 5 votes vote down vote up
/**
 * Approx. time spent in gc. See {@link GarbageCollectorMXBean}
 */
public long getCollectionTime() {
    long garbageCollectionTime = 0;
    for (GarbageCollectorMXBean gc : ManagementFactory.getGarbageCollectorMXBeans()) {
        long time = gc.getCollectionTime();
        if (time >= 0) {
            garbageCollectionTime += time;
        }
    }
    return garbageCollectionTime;
}
 
Example 41
Project: angel   File: CounterUpdater.java   Source Code and License 5 votes vote down vote up
/**
 * @return the number of milliseconds that the gc has used for CPU since the last time this
 *         method was called.
 */
protected long getElapsedGc() {
  long thisGcMillis = 0;
  for (GarbageCollectorMXBean gcBean : gcBeans) {
    thisGcMillis += gcBean.getCollectionTime();
  }

  long delta = thisGcMillis - lastGcMillis;
  this.lastGcMillis = thisGcMillis;
  return delta;
}
 
Example 42
Project: hadoop-oss   File: JvmMetrics.java   Source Code and License 5 votes vote down vote up
private void doGarbageCollectionUpdates() {
    List<GarbageCollectorMXBean> gcBeans =
            ManagementFactory.getGarbageCollectorMXBeans();
    long count = 0;
    long timeMillis = 0;
    for (GarbageCollectorMXBean gcBean : gcBeans) {
        count += gcBean.getCollectionCount();
        timeMillis += gcBean.getCollectionTime();
    }
    metrics.incrMetric("gcCount", (int)(count - gcCount));
    metrics.incrMetric("gcTimeMillis", (int)(timeMillis - gcTimeMillis));
    
    gcCount = count;
    gcTimeMillis = timeMillis;
}
 
Example 43
Project: hadoop-oss   File: JvmPauseMonitor.java   Source Code and License 5 votes vote down vote up
private Map<String, GcTimes> getGcTimes() {
  Map<String, GcTimes> map = Maps.newHashMap();
  List<GarbageCollectorMXBean> gcBeans =
      ManagementFactory.getGarbageCollectorMXBeans();
  for (GarbageCollectorMXBean gcBean : gcBeans) {
    map.put(gcBean.getName(), new GcTimes(gcBean));
  }
  return map;
}
 
Example 44
Project: javametrics   File: GCDataProvider.java   Source Code and License 5 votes vote down vote up
private static long getTotalCollectionTime() {
    List<GarbageCollectorMXBean> sunBeans = ManagementFactory.getGarbageCollectorMXBeans();
    long totalCollectionTime = 0;
    if (sunBeans.size() == 0) {
        return -1;
    }
    for (Iterator<GarbageCollectorMXBean> iterator = sunBeans.iterator(); iterator.hasNext();) {
        GarbageCollectorMXBean garbageCollectorMXBean = iterator.next();
        long collectionTime = garbageCollectorMXBean.getCollectionTime();
        if( collectionTime != -1) {
            totalCollectionTime += collectionTime;
        }
    }
    return totalCollectionTime;
}
 
Example 45
Project: fiery   File: Toolbox.java   Source Code and License 5 votes vote down vote up
public static String getGCStats() {
    long totalGC = 0;
    long gcTime = 0;

    for (GarbageCollectorMXBean gc : ManagementFactory.getGarbageCollectorMXBeans()) {
        long count = gc.getCollectionCount();

        if (count >= 0) {
            totalGC += count;
        }

        long time = gc.getCollectionTime();

        if (time >= 0) {
            gcTime += time;
        }
    }

    StringBuilder sb = new StringBuilder();

    sb.append(banner("memory stats"));
    sb.append("\n- total collections: " + totalGC);
    sb.append("\n- total collection time: " + formatTime(gcTime));

    Runtime runtime = Runtime.getRuntime();
    sb.append("\n- total memory: " + printMem(runtime.totalMemory()));

    return sb.toString();
}
 
Example 46
Project: Rubus   File: GCSnapshot.java   Source Code and License 5 votes vote down vote up
public long accumulatedInvocations()
{
    long sum = 0;
    int i = 0;
    for (GarbageCollectorMXBean bean : garbageBeans)
    {
        sum += bean.getCollectionCount() - gcInvocations[i++];
    }
    return sum;
}
 
Example 47
Project: Rubus   File: GCSnapshot.java   Source Code and License 5 votes vote down vote up
public long accumulatedTime()
{
    long sum = 0;
    int i = 0;
    for (GarbageCollectorMXBean bean : garbageBeans)
    {
        sum += bean.getCollectionTime() - gcTimes[i++];
    }
    return sum;
}
 
Example 48
Project: rskj   File: VMPerformanceTest.java   Source Code and License 5 votes vote down vote up
long getGarbageCollectorTimeMillis()
{
    long t=0;
    List<GarbageCollectorMXBean> gcs = ManagementFactory.getGarbageCollectorMXBeans();
    for (GarbageCollectorMXBean gc :gcs) {
        t +=gc.getCollectionTime();
    }
    return t;
}
 
Example 49
Project: OpenJSharp   File: JvmMemGCTableMetaImpl.java   Source Code and License 5 votes vote down vote up
/**
 * Returns the data associated with the given index.
 * If the given index is not found, null is returned.
 * Note that returning null does not necessarily means that
 * the index was not found.
 **/
public Object  getData(SnmpTableHandler handler, SnmpOid index) {
    final Object value = handler.getData(index);
    if (value instanceof GarbageCollectorMXBean) return value;
    // Behaves as if there was nothing at this index...
    //
    return null;
}
 
Example 50
Project: OpenJSharp   File: JvmMemGCTableMetaImpl.java   Source Code and License 5 votes vote down vote up
/**
 * Returns true if the given <var>index</var> is present.
 **/
public boolean contains(SnmpTableHandler handler, SnmpOid index) {
    if (handler.getData(index) instanceof GarbageCollectorMXBean)
        return true;
    // Behaves as if there was nothing at this index...
    //
    return false;
}
 
Example 51
Project: monarch   File: VMStats50.java   Source Code and License 5 votes vote down vote up
private void initGC() {
  List<GarbageCollectorMXBean> l = ManagementFactory.getGarbageCollectorMXBeans();
  for (GarbageCollectorMXBean item : l) {
    if (item.isValid() && !gcMap.containsKey(item)) {
      gcMap.put(item, this.f.createStatistics(gcType, item.getName(), this.id));
    }
  }
}
 
Example 52
Project: monarch   File: VMStats50.java   Source Code and License 5 votes vote down vote up
private void refreshGC() {
  Iterator<Map.Entry<GarbageCollectorMXBean, Statistics>> it = gcMap.entrySet().iterator();
  while (it.hasNext()) {
    Map.Entry<GarbageCollectorMXBean, Statistics> me = it.next();
    GarbageCollectorMXBean gc = me.getKey();
    Statistics s = me.getValue();
    if (!gc.isValid()) {
      s.close();
      it.remove();
    } else {
      s.setLong(gc_collectionsId, gc.getCollectionCount());
      s.setLong(gc_collectionTimeId, gc.getCollectionTime());
    }
  }
}
 
Example 53
Project: MaxSim   File: HumongousAlloc.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) throws InterruptedException {
    allocate((int) (size * MB), sleepTime, sleepFreq);
    List<GarbageCollectorMXBean> collectors = ManagementFactory.getGarbageCollectorMXBeans();
    for (GarbageCollectorMXBean collector : collectors) {
        if (collector.getName().contains("G1 Old")) {
           long count = collector.getCollectionCount();
            if (count > 0) {
                throw new RuntimeException("Failed: FullGCs should not have happened. The number of FullGC run is " + count);
            }
            else {
                System.out.println("Passed.");
            }
        }
    }
}
 
Example 54
Project: hadoop   File: Task.java   Source Code and License 5 votes vote down vote up
/**
 * @return the number of milliseconds that the gc has used for CPU
 * since the last time this method was called.
 */
protected long getElapsedGc() {
  long thisGcMillis = 0;
  for (GarbageCollectorMXBean gcBean : gcBeans) {
    thisGcMillis += gcBean.getCollectionTime();
  }

  long delta = thisGcMillis - lastGcMillis;
  this.lastGcMillis = thisGcMillis;
  return delta;
}
 
Example 55
Project: hadoop   File: JvmMetrics.java   Source Code and License 5 votes vote down vote up
private void doGarbageCollectionUpdates() {
    List<GarbageCollectorMXBean> gcBeans =
            ManagementFactory.getGarbageCollectorMXBeans();
    long count = 0;
    long timeMillis = 0;
    for (GarbageCollectorMXBean gcBean : gcBeans) {
        count += gcBean.getCollectionCount();
        timeMillis += gcBean.getCollectionTime();
    }
    metrics.incrMetric("gcCount", (int)(count - gcCount));
    metrics.incrMetric("gcTimeMillis", (int)(timeMillis - gcTimeMillis));
    
    gcCount = count;
    gcTimeMillis = timeMillis;
}
 
Example 56
Project: hadoop   File: JvmPauseMonitor.java   Source Code and License 5 votes vote down vote up
private Map<String, GcTimes> getGcTimes() {
  Map<String, GcTimes> map = Maps.newHashMap();
  List<GarbageCollectorMXBean> gcBeans =
      ManagementFactory.getGarbageCollectorMXBeans();
  for (GarbageCollectorMXBean gcBean : gcBeans) {
    map.put(gcBean.getName(), new GcTimes(gcBean));
  }
  return map;
}
 
Example 57
Project: jdk8u-jdk   File: JvmMemGCTableMetaImpl.java   Source Code and License 5 votes vote down vote up
/**
 * Returns the data associated with the given index.
 * If the given index is not found, null is returned.
 * Note that returning null does not necessarily means that
 * the index was not found.
 **/
public Object  getData(SnmpTableHandler handler, SnmpOid index) {
    final Object value = handler.getData(index);
    if (value instanceof GarbageCollectorMXBean) return value;
    // Behaves as if there was nothing at this index...
    //
    return null;
}
 
Example 58
Project: jdk8u-jdk   File: JvmMemGCTableMetaImpl.java   Source Code and License 5 votes vote down vote up
/**
 * Returns true if the given <var>index</var> is present.
 **/
public boolean contains(SnmpTableHandler handler, SnmpOid index) {
    if (handler.getData(index) instanceof GarbageCollectorMXBean)
        return true;
    // Behaves as if there was nothing at this index...
    //
    return false;
}
 
Example 59
Project: jdk8u-jdk   File: MXBeanInteropTest1.java   Source Code and License 5 votes vote down vote up
private final int doGarbageCollectorMXBeanTest(MBeanServerConnection mbsc) {
    int errorCount = 0 ;
    System.out.println("---- GarbageCollectorMXBean") ;

    try {
        ObjectName filterName =
                new ObjectName(ManagementFactory.GARBAGE_COLLECTOR_MXBEAN_DOMAIN_TYPE
                + ",*");
        Set<ObjectName> onSet = mbsc.queryNames(filterName, null);

        for (Iterator<ObjectName> iter = onSet.iterator(); iter.hasNext(); ) {
            ObjectName garbageName = iter.next() ;
            System.out.println("-------- " + garbageName) ;
            MBeanInfo mbInfo = mbsc.getMBeanInfo(garbageName);
            errorCount += checkNonEmpty(mbInfo);
            System.out.println("getMBeanInfo\t\t" + mbInfo);
            GarbageCollectorMXBean garbage = null ;

            garbage =
                    JMX.newMXBeanProxy(mbsc,
                    garbageName,
                    GarbageCollectorMXBean.class) ;
            System.out.println("getCollectionCount\t\t"
                    + garbage.getCollectionCount());
            System.out.println("getCollectionTime\t\t"
                    + garbage.getCollectionTime());
        }

        System.out.println("---- OK\n") ;
    } catch (Exception e) {
        Utils.printThrowable(e, true) ;
        errorCount++ ;
        System.out.println("---- ERROR\n") ;
    }

    return errorCount ;
}
 
Example 60
Project: aurora-prometheus   File: JvmGcMetrics.java   Source Code and License 5 votes vote down vote up
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);
    }
}