Java Code Examples for java.lang.management.GarbageCollectorMXBean#getCollectionTime()

The following examples show how to use java.lang.management.GarbageCollectorMXBean#getCollectionTime() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: JvmMetrics.java    From hadoop with Apache License 2.0 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 2
Source File: GcTimeUpdater.java    From tez with Apache License 2.0 5 votes vote down vote up
public long getCumulativaGcTime() {
  long thisGcMillis = 0;
  for (GarbageCollectorMXBean gcBean : gcBeans) {
    thisGcMillis += gcBean.getCollectionTime();
  }
  return thisGcMillis;
}
 
Example 3
Source File: JvmPropertyPolicy.java    From TarsJava with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public String get() {
    for (GarbageCollectorMXBean gcMXBean : ManagementFactory.getGarbageCollectorMXBeans()) {
        if (gcName.equals(gcMXBean.getName())) {
            long gcTime = gcMXBean.getCollectionTime();
            long t = gcTime - lastGCTime;
            lastGCTime = gcTime;
            return String.valueOf(t);
        }
    }
    return "0";
}
 
Example 4
Source File: GCState.java    From jstorm with Apache License 2.0 5 votes vote down vote up
public static Object getOldGenCollectionTime() {
    long fullGCTime = 0L;
    List<GarbageCollectorMXBean> list = ManagementFactory.getGarbageCollectorMXBeans();
    for (GarbageCollectorMXBean gmx : list) {
        if(OldGenCollectorNames.contains(gmx.getName())){
            fullGCTime+=gmx.getCollectionTime();

        }
    }
    return fullGCTime;
}
 
Example 5
Source File: GcProfiler.java    From cache2k-benchmark with Apache License 2.0 5 votes vote down vote up
@Override
public void beforeIteration(BenchmarkParams benchmarkParams, IterationParams iterationParams) {
  installHooks();

  long gcTime = 0;
  long gcCount = 0;
  for (GarbageCollectorMXBean bean : ManagementFactory.getGarbageCollectorMXBeans()) {
    gcCount += bean.getCollectionCount();
    gcTime += bean.getCollectionTime();
  }
  this.beforeGCCount = gcCount;
  this.beforeGCTime = gcTime;
  this.beforeAllocated = HotspotAllocationSnapshot.create();
  this.beforeTime = System.nanoTime();
}
 
Example 6
Source File: JvmMetrics.java    From big-c with Apache License 2.0 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 7
Source File: GcTimeUpdater.java    From incubator-tez with Apache License 2.0 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 8
Source File: GCStatsGetter.java    From s2g-zuul with MIT License 5 votes vote down vote up
@Override
public Stats get() {

    List<GarbageCollectorMXBean> beans = ManagementFactory.getGarbageCollectorMXBeans();
    int minorGcCount=0, fullGcCount=0, otherGcCount=0;
    long minorGcTime=0, fullGcTime=0, otherGcTime=0;
    for (GarbageCollectorMXBean b : beans) {
        String name = b.getName();
        if (young.contains(name)) {
            minorGcCount += b.getCollectionCount();
            minorGcTime += b.getCollectionTime();
        }else if (old.contains(name)) {
            fullGcCount += b.getCollectionCount();
            fullGcTime += b.getCollectionTime();
        }else{
            otherGcCount += b.getCollectionCount();
            otherGcTime += b.getCollectionTime();
        }
    }

    GCStats s = new GCStats();
    s.setMinorGcCount(minorGcCount - previous.getMinorGcCount());
    s.setMinorGcTime(minorGcTime - previous.getMinorGcTime());
    s.setFullGcCount(fullGcCount - previous.getFullGcCount());
    s.setFullGcTime(fullGcTime - previous.getFullGcTime());
    s.setOtherGcCount(otherGcCount - previous.getOtherGcCount());
    s.setOtherGcCount(otherGcTime - previous.getOtherGcTime());

    previous.setMinorGcCount(minorGcCount);
    previous.setMinorGcTime(minorGcTime);
    previous.setFullGcCount(fullGcCount);
    previous.setFullGcTime(fullGcTime);
    previous.setOtherGcCount(otherGcCount);
    previous.setOtherGcCount(otherGcTime);

    return s;
}
 
Example 9
Source File: GCHelper.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
public static CollectionSummary createFromMxBeans() {
    CollectionSummary summary = new CollectionSummary();
    List<GarbageCollectorMXBean> gcBeans = ManagementFactory.getGarbageCollectorMXBeans();
    for (int c=0; c<gcBeans.size(); c++) {
        GarbageCollectorMXBean currBean = gcBeans.get(c);
        Boolean isYoung = beanCollectorTypes.get(currBean.getName());
        assertNotNull(isYoung, "Unknown MXBean name: " + currBean.getName());
        long collectionTime = currBean.getCollectionTime() * 1000; // Convert from millis to micros.
        summary.add(currBean.getName(), isYoung.booleanValue(), currBean.getCollectionCount(), collectionTime);
    }
    return summary;
}
 
Example 10
Source File: FlowController.java    From nifi with Apache License 2.0 5 votes vote down vote up
public List<GarbageCollectionStatus> getGarbageCollectionStatus() {
    final List<GarbageCollectionStatus> statuses = new ArrayList<>();

    final Date now = new Date();
    for (final GarbageCollectorMXBean mbean : ManagementFactory.getGarbageCollectorMXBeans()) {
        final String managerName = mbean.getName();
        final long count = mbean.getCollectionCount();
        final long millis = mbean.getCollectionTime();
        final GarbageCollectionStatus status = new StandardGarbageCollectionStatus(managerName, now, count, millis);
        statuses.add(status);
    }

    return statuses;
}
 
Example 11
Source File: Footprint.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
public long getCollectionTime() {
    long sum = 0;
    for (GarbageCollectorMXBean gcBean : clist) {
        sum += gcBean.getCollectionTime();
    }
    return sum;
}
 
Example 12
Source File: JvmMetrics.java    From RDFS with Apache License 2.0 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 13
Source File: MemoryInformations.java    From javamelody with Apache License 2.0 5 votes vote down vote up
private static long buildGarbageCollectionTimeMillis() {
	long garbageCollectionTime = 0;
	for (final GarbageCollectorMXBean garbageCollector : ManagementFactory
			.getGarbageCollectorMXBeans()) {
		garbageCollectionTime += garbageCollector.getCollectionTime();
	}
	return garbageCollectionTime;
}
 
Example 14
Source File: MemoryMonitor.java    From beam with Apache License 2.0 5 votes vote down vote up
@Override
public long totalGCTimeMilliseconds() {
  long inGC = 0;
  for (GarbageCollectorMXBean gc : ManagementFactory.getGarbageCollectorMXBeans()) {
    inGC += gc.getCollectionTime();
  }
  return inGC;
}
 
Example 15
Source File: GarbageCollectorMetric.java    From neural with MIT License 5 votes vote down vote up
/**
 * ps_scavenge.count:新生代PS(并行扫描)次数
 * ps_scavenge.time:单位:秒,新生代PS(并行扫描)时间
 * ps_marksweep.count:老年代CMS(并行标记清扫)次数
 * ps_marksweep_time:单位:秒,老年代CMS(并行标记清扫)时间
 * <p>
 * ps_scavenge_diff_count:新生代PS(并行扫描)变化次数
 * ps_scavenge_diff_time: 单位:秒,新生代PS(并行扫描)变化时间
 * ps_marksweep_diff_count: 老年代CMS(并行标记清扫)变化次数
 * ps_marksweep_diff_time: 单位:秒,老年代CMS(并行标记清扫)变化时间
 */
public Map<String, Double> getData() {
    final Map<String, Double> gauges = new LinkedHashMap<String, Double>();

    for (final GarbageCollectorMXBean gc : garbageCollectors) {
        final String name = "gc_" + WHITESPACE.matcher(gc.getName()).replaceAll("_").toLowerCase();

        String lastCountKey = name + "_diff_count";
        Object lastCountVal = lastMetric.get(lastCountKey);
        lastCountVal = (lastCountVal == null) ? 0 : lastCountVal;
        long lastCountCurrent = gc.getCollectionCount();
        long lastCountKv = lastCountCurrent - Long.valueOf(lastCountVal + "");
        lastMetric.put(lastCountKey, lastCountCurrent);
        gauges.put(lastCountKey, (double) lastCountKv);

        String lastTimeKey = name + "_diff_time";
        Object lastTimeVal = lastMetric.get(lastTimeKey);
        lastTimeVal = (lastTimeVal == null) ? 0 : lastTimeVal;
        Double lastTimeCurrent = (double) gc.getCollectionTime();
        double lastTimeKv = lastTimeCurrent - Double.valueOf(lastTimeVal + "");
        lastMetric.put(lastTimeKey, lastTimeCurrent);
        gauges.put(lastTimeKey, Double.valueOf(String.format("%.3f", lastTimeKv / 1000)));

        gauges.put(name + "_count", (double) lastCountCurrent);
        // 单位:从毫秒转换为秒
        gauges.put(name + "_time", Double.valueOf(String.format("%.3f", lastTimeCurrent / 1000)));
    }

    return gauges;
}
 
Example 16
Source File: CustomGarbageCollectorMetricSet.java    From dr-elephant with Apache License 2.0 4 votes vote down vote up
/**
 * @return Returns a map of defined gauges.
 */
@Override
public Map<String, Metric> getMetrics() {
  final Map<String, Metric> gauges = new HashMap<String, Metric>();

  long cumulativeGCTime = 0L;

  for (final GarbageCollectorMXBean gc : garbageCollectors) {
    final String name = WHITESPACE.matcher(gc.getName()).replaceAll("-");

    gauges.put(name(name, "count"), new Gauge<Long>() {
      @Override
      public Long getValue() {
        return gc.getCollectionCount();
      }
    });

    gauges.put(name(name, "time"), new Gauge<Long>() {
      @Override
      public Long getValue() {
        return gc.getCollectionTime();
      }
    });

    cumulativeGCTime += gc.getCollectionTime();
  }

  final long uptime = ManagementFactory.getRuntimeMXBean().getUptime();
  final Double gc2UptimeRatio = (double)cumulativeGCTime / uptime;

  gauges.put("jvmUptime", new Gauge<Long>() {
    @Override
    public Long getValue() {
      return uptime;
    }
  });

  gauges.put("gc2UptimeRatio", new Gauge<Double>() {
    @Override
    public Double getValue() {
      return gc2UptimeRatio;
    }
  });

  return Collections.unmodifiableMap(gauges);
}
 
Example 17
Source File: JvmPauseMonitor.java    From hadoop with Apache License 2.0 4 votes vote down vote up
private GcTimes(GarbageCollectorMXBean gcBean) {
  gcCount = gcBean.getCollectionCount();
  gcTimeMillis = gcBean.getCollectionTime();
}
 
Example 18
Source File: GcProfiler.java    From cache2k-benchmark with Apache License 2.0 4 votes vote down vote up
@Override
public Collection<? extends Result> afterIteration(BenchmarkParams benchmarkParams, IterationParams iterationParams, IterationResult iResult) {

  try {
    Thread.sleep(567);
  } catch (InterruptedException ignore) {

  }

  uninstallHooks();
  long afterTime = System.nanoTime();

  HotspotAllocationSnapshot newSnapshot = HotspotAllocationSnapshot.create();

  long gcTime = 0;
  long gcCount = 0;
  for (GarbageCollectorMXBean bean : ManagementFactory.getGarbageCollectorMXBeans()) {
    gcCount += bean.getCollectionCount();
    gcTime += bean.getCollectionTime();
  }

  List<Result<?>> results = new ArrayList<>();

  if (beforeAllocated == HotspotAllocationSnapshot.EMPTY) {
    results.add(new ScalarResult(Defaults.PREFIX + "gc.alloc.rate",
      Double.NaN,
      "MB/sec", AggregationPolicy.AVG));
  } else {
    long allocated = newSnapshot.subtract(beforeAllocated);
    results.add(new ScalarResult(Defaults.PREFIX + "gc.alloc.rate",
      (afterTime != beforeTime) ?
        1.0 * allocated / 1024 / 1024 * TimeUnit.SECONDS.toNanos(1) / (afterTime - beforeTime) :
        Double.NaN,
      "MB/sec", AggregationPolicy.AVG));
    if (allocated != 0) {
      long allOps = iResult.getMetadata().getAllOps();
      results.add(new ScalarResult(Defaults.PREFIX + "gc.alloc.rate.norm",
        (allOps != 0) ?
          1.0 * allocated / allOps :
          Double.NaN,
        "B/op", AggregationPolicy.AVG));
    }
  }

  results.add(new ScalarResult(
    Defaults.PREFIX + "gc.count",
    gcCount - beforeGCCount,
    "counts",
    AggregationPolicy.AVG));

  if (gcCount != beforeGCCount || gcTime != beforeGCTime) {
    results.add(new ScalarResult(
      Defaults.PREFIX + "gc.time",
      gcTime - beforeGCTime,
      "ms",
      AggregationPolicy.AVG));
  }

  for (String space : churn.keys()) {
    double churnRate = (afterTime != beforeTime) ?
      1.0 * churn.count(space) * TimeUnit.SECONDS.toNanos(1) / (afterTime - beforeTime) / 1024 / 1024 :
      Double.NaN;

    double churnNorm = 1.0 * churn.count(space) / iResult.getMetadata().getAllOps();

    String spaceName = space.replaceAll(" ", "_");

    results.add(new ScalarResult(
      Defaults.PREFIX + "gc.churn." + spaceName + "",
      churnRate,
      "MB/sec",
      AggregationPolicy.AVG));

    results.add(new ScalarResult(Defaults.PREFIX + "gc.churn." + spaceName + ".norm",
      churnNorm,
      "B/op",
      AggregationPolicy.AVG));
  }

  if (!usedAfterGc.isEmpty()) {
    Collections.sort(usedAfterGc);
    long _maximumUsedAfterGc = usedAfterGc.get(usedAfterGc.size() - 1);
    results.add(new ScalarResult(Defaults.PREFIX + "gc.maximumUsedAfterGc",
      _maximumUsedAfterGc,
      "bytes",
      AggregationPolicy.AVG));
    System.out.println("maximumUsedAfterGc=" + _maximumUsedAfterGc);
  }
  if (!committedAfterGc.isEmpty()) {
    Collections.sort(committedAfterGc);
    long _committedUsedAfterGc = committedAfterGc.get(committedAfterGc.size() - 1);
    results.add(new ScalarResult(Defaults.PREFIX + "gc.maximumCommittedAfterGc",
      _committedUsedAfterGc,
      "bytes",
      AggregationPolicy.AVG));
    System.out.println("maximumCommittedAfterGc=" + _committedUsedAfterGc);
  }

  return results;
}
 
Example 19
Source File: JvmPauseMonitor.java    From big-c with Apache License 2.0 4 votes vote down vote up
private GcTimes(GarbageCollectorMXBean gcBean) {
  gcCount = gcBean.getCollectionCount();
  gcTimeMillis = gcBean.getCollectionTime();
}
 
Example 20
Source File: JvmInfo.java    From elasticsearch-helper with Apache License 2.0 4 votes vote down vote up
public static Stats readStats() {
    Stats stats = new Stats();
    stats.timestamp = System.currentTimeMillis();
    stats.uptime = runtimeMXBean.getUptime();
    stats.mem = new Mem();

    MemoryUsage memUsage = memoryMXBean.getHeapMemoryUsage();
    stats.mem.heapInit = memUsage.getInit() < 0 ? 0 : memUsage.getInit();
    stats.mem.heapUsed = memUsage.getUsed() < 0 ? 0 : memUsage.getUsed();
    stats.mem.heapCommitted = memUsage.getCommitted() < 0 ? 0 : memUsage.getCommitted();
    stats.mem.heapMax = memUsage.getMax() < 0 ? 0 : memUsage.getMax();

    memUsage = memoryMXBean.getNonHeapMemoryUsage();
    stats.mem.nonHeapInit = memUsage.getInit() < 0 ? 0 : memUsage.getInit();
    stats.mem.nonHeapUsed = memUsage.getUsed() < 0 ? 0 : memUsage.getUsed();
    stats.mem.nonHeapCommitted = memUsage.getCommitted() < 0 ? 0 : memUsage.getCommitted();
    stats.mem.nonHeapMax = memUsage.getMax() < 0 ? 0 : memUsage.getMax();

    List<MemoryPoolMXBean> memoryPoolMXBeans = ManagementFactory.getMemoryPoolMXBeans();
    List<MemoryPool> pools = new ArrayList<>();
    for (int i = 0; i < memoryPoolMXBeans.size(); i++) {
        try {
            MemoryPoolMXBean memoryPoolMXBean = memoryPoolMXBeans.get(i);
            MemoryUsage usage = memoryPoolMXBean.getUsage();
            MemoryUsage peakUsage = memoryPoolMXBean.getPeakUsage();
            String name = getByMemoryPoolName(memoryPoolMXBean.getName(), null);
            if (name == null) { // if we can't resolve it, its not interesting.... (Per Gen, Code Cache)
                continue;
            }
            pools.add(new MemoryPool(name,
                    usage.getUsed() < 0 ? 0 : usage.getUsed(),
                    usage.getMax() < 0 ? 0 : usage.getMax(),
                    peakUsage.getUsed() < 0 ? 0 : peakUsage.getUsed(),
                    peakUsage.getMax() < 0 ? 0 : peakUsage.getMax()
            ));
        } catch (OutOfMemoryError err) {
            throw err; // rethrow
        } catch (Throwable ex) {
            /* ignore some JVMs might barf here with:
             * java.lang.InternalError: Memory Pool not found
             * we just omit the pool in that case!*/
        }
    }
    stats.mem.pools = pools.toArray(new MemoryPool[pools.size()]);

    stats.threads = new Threads();
    stats.threads.count = threadMXBean.getThreadCount();
    stats.threads.peakCount = threadMXBean.getPeakThreadCount();



    List<GarbageCollectorMXBean> gcMxBeans = ManagementFactory.getGarbageCollectorMXBeans();
    stats.gc = new GarbageCollectors();
    stats.gc.collectors = new GarbageCollector[gcMxBeans.size()];
    for (int i = 0; i < stats.gc.collectors.length; i++) {
        GarbageCollectorMXBean gcMxBean = gcMxBeans.get(i);
        stats.gc.collectors[i] = new GarbageCollector();
        stats.gc.collectors[i].name = getByGcName(gcMxBean.getName(), gcMxBean.getName());
        stats.gc.collectors[i].collectionCount = gcMxBean.getCollectionCount();
        stats.gc.collectors[i].collectionTime = gcMxBean.getCollectionTime();
    }

    try {
        List<BufferPoolMXBean> bufferPools = ManagementFactory.getPlatformMXBeans(BufferPoolMXBean.class);
        stats.bufferPools = new ArrayList<>(bufferPools.size());
        for (BufferPoolMXBean bufferPool : bufferPools) {
            stats.bufferPools.add(new BufferPool(bufferPool.getName(), bufferPool.getCount(), bufferPool.getTotalCapacity(), bufferPool.getMemoryUsed()));
        }
    } catch (Throwable t) {
        // buffer pools are not available
    }

    stats.classes = new Classes();
    stats.classes.loadedClassCount = classLoadingMXBean.getLoadedClassCount();
    stats.classes.totalLoadedClassCount = classLoadingMXBean.getTotalLoadedClassCount();
    stats.classes.unloadedClassCount = classLoadingMXBean.getUnloadedClassCount();

    return stats;
}