@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); } } }
private void reportUsage(MemoryPoolMXBean mxBean, MetricRecorder.Context metricContext) { String name = mxBean.getName(); Metric usedMetric = Metric.define("MemoryPoolUsed_" + name); Metric maxMetric = Metric.define("MemoryPoolMax_" + name); Metric percMetric = Metric.define("MemoryPoolUsage_" + name); MemoryUsage usage = mxBean.getUsage(); long used = usage.getUsed(); long max = usage.getMax(); metricContext.record(usedMetric, used / M, Unit.MEGABYTE); // max can be undefined (-1) https://docs.oracle.com/javase/8/docs/api/java/lang/management/MemoryUsage.html if (max >= 0) { metricContext.record(maxMetric, max / M, Unit.MEGABYTE); double used_percent = 100.0 * ((double)used/(double)max); metricContext.record(percMetric, used_percent, Unit.PERCENT); } }
/** * WARNING: This should probably be moved to JvmMemPoolTableMetaImpl **/ private int findInCache(SnmpTableHandler handler, String poolName) { if (!(handler instanceof SnmpCachedData)) { if (handler != null) { final String err = "Bad class for JvmMemPoolTable datas: " + handler.getClass().getName(); log.error("getJvmMemPoolEntry", err); } return -1; } final SnmpCachedData data = (SnmpCachedData)handler; final int len = data.datas.length; for (int i=0; i < data.datas.length ; i++) { final MemoryPoolMXBean pool = (MemoryPoolMXBean) data.datas[i]; if (poolName.equals(pool.getName())) return i; } return -1; }
/** * Builds a map pool-name => pool-index from the SnmpTableHandler * of the JvmMemPoolTable. **/ private static Map<String, SnmpOid> buildPoolIndexMap(SnmpTableHandler handler) { // optimization... if (handler instanceof SnmpCachedData) return buildPoolIndexMap((SnmpCachedData)handler); // not optimizable... too bad. final Map<String, SnmpOid> m = new HashMap<>(); SnmpOid index=null; while ((index = handler.getNext(index))!=null) { final MemoryPoolMXBean mpm = (MemoryPoolMXBean)handler.getData(index); if (mpm == null) continue; final String name = mpm.getName(); if (name == null) continue; m.put(name,index); } return m; }
/** * Builds a map pool-name => pool-index from the SnmpTableHandler * of the JvmMemPoolTable. * Optimized algorithm. **/ private static Map<String, SnmpOid> buildPoolIndexMap(SnmpCachedData cached) { if (cached == null) return Collections.emptyMap(); final SnmpOid[] indexes = cached.indexes; final Object[] datas = cached.datas; final int len = indexes.length; final Map<String, SnmpOid> m = new HashMap<>(len); for (int i=0; i<len; i++) { final SnmpOid index = indexes[i]; if (index == null) continue; final MemoryPoolMXBean mpm = (MemoryPoolMXBean)datas[i]; if (mpm == null) continue; final String name = mpm.getName(); if (name == null) continue; m.put(name,index); } return m; }
/** * Determines if the name of the memory pool MXBean provided matches a list of known tenured pool * names. * * Package private for testing. * * @param memoryPoolMXBean The memory pool MXBean to check. * @return True if the pool name matches a known tenured pool name, false otherwise. */ static boolean isTenured(MemoryPoolMXBean memoryPoolMXBean) { if (memoryPoolMXBean.getType() != MemoryType.HEAP) { return false; } String name = memoryPoolMXBean.getName(); return name.equals("CMS Old Gen") // Sun Concurrent Mark Sweep GC || name.equals("PS Old Gen") // Sun Parallel GC || name.equals("G1 Old Gen") // Sun G1 GC || name.equals("Old Space") // BEA JRockit 1.5, 1.6 GC || name.equals("Tenured Gen") // Hitachi 1.5 GC || name.equals("Java heap") // IBM 1.5, 1.6 GC || name.equals("GenPauseless Old Gen") // azul C4/GPGC collector // Allow an unknown pool name to monitor || (HEAP_POOL != null && name.equals(HEAP_POOL)); }
/** * Returns the names of all available memory pools as a single string. */ private static String getAllMemoryPoolNames() { StringBuilder builder = new StringBuilder("["); for (MemoryPoolMXBean memoryPoolBean : ManagementFactory.getMemoryPoolMXBeans()) { builder.append("(Name=").append(memoryPoolBean.getName()).append(";Type=") .append(memoryPoolBean.getType()).append(";UsageThresholdSupported=") .append(memoryPoolBean.isUsageThresholdSupported()).append("), "); } if (builder.length() > 1) { builder.setLength(builder.length() - 2); } builder.append("]"); return builder.toString(); }
/** * 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); }
public static void initCodeSizeLimits(int nMaxSizeMemPoolCodeCache, int nMaxSizeMemPoolPermGen) { // PJD remove ibm JMV List<MemoryPoolMXBean> pools = ManagementFactory.getMemoryPoolMXBeans(); for (MemoryPoolMXBean p: pools) { if(p.getType().compareTo(MemoryType.NON_HEAP) == 0) { String cs = p.getName(); if(cs.equalsIgnoreCase("Code Cache")) p.setUsageThreshold((long)nMaxSizeMemPoolCodeCache * 1024L * 1024L); else if(cs.equalsIgnoreCase("Perm Gen")) p.setUsageThreshold((long)nMaxSizeMemPoolPermGen * 1024L * 1024L); } } }
private void setMemThreshold() { m_bMaxPermanentHeap_MoSet = false; List<MemoryPoolMXBean> pools = ManagementFactory.getMemoryPoolMXBeans(); for (MemoryPoolMXBean p: pools) { if(p.getType().compareTo(MemoryType.HEAP) == 0) { String cs = p.getName(); if(cs.equalsIgnoreCase("Tenured gen")) { long l = 1024L * 1024L * (long)m_nMaxPermanentHeap_Mo; p.setUsageThreshold(l); m_tenuredPool = p; } } } }
/** * Returns a summary information about the memory pools. */ public static String poolSummaries() { // Why ? list-archive?4273859 // How ? http://stackoverflow.com/questions/697336/how-do-i-programmatically-find-out-my-permgen-space-usage // http://stackoverflow.com/questions/8356416/xxmaxpermsize-with-or-without-xxpermsize StringBuilder sb = new StringBuilder(); Iterator<MemoryPoolMXBean> iter = ManagementFactory.getMemoryPoolMXBeans().iterator(); while (iter.hasNext()) { MemoryPoolMXBean item = iter.next(); String name = item.getName(); MemoryType type = item.getType(); MemoryUsage usage = item.getUsage(); MemoryUsage peak = item.getPeakUsage(); MemoryUsage collections = item.getCollectionUsage(); sb.append(String.format("Memory pool name: " + name + ", type: " + type + ", usage: " + usage + ", peak: " + peak + ", collections: " + collections + "\n")); } return sb.toString(); }
private List<Object> eatMetaspace(float targetUsage) { List<Object> list = new ArrayList<>(); MemoryPoolMXBean metaspacePool = getMatchedMemoryPool(".*Metaspace.*"); float currentUsage; GeneratedClassProducer gp = new GeneratedClassProducer(); do { try { list.add(gp.create(0)); } catch (OutOfMemoryError oome) { list = null; throw new RuntimeException("Unexpected OOME '" + oome.getMessage() + "' while eating " + targetUsage + " of Metaspace."); } MemoryUsage memoryUsage = metaspacePool.getUsage(); currentUsage = (((float) memoryUsage.getUsed()) / memoryUsage.getMax()); } while (currentUsage < targetUsage); return list; }
protected void runTest() { long headerSize = CodeCacheUtils.getHeaderSize(btype); long allocationUnit = Math.max(0, CodeCacheUtils.MIN_ALLOCATION - headerSize); MemoryPoolMXBean bean = btype.getMemoryPool(); long initialCount = bean.getUsageThresholdCount(); long initialSize = bean.getUsage().getUsed(); bean.setUsageThreshold(initialSize + THRESHOLD_STEP); for (int i = 0; i < ALLOCATION_STEP - 1; i++) { CodeCacheUtils.WB.allocateCodeBlob(allocationUnit, btype.id); } // Usage threshold check is triggered by GC cycle, so, call it CodeCacheUtils.WB.fullGC(); checkUsageThresholdCount(bean, initialCount); long filledSize = bean.getUsage().getUsed(); bean.setUsageThreshold(filledSize + THRESHOLD_STEP); for (int i = 0; i < ALLOCATION_STEP - 1; i++) { CodeCacheUtils.WB.allocateCodeBlob(allocationUnit, btype.id); } CodeCacheUtils.WB.fullGC(); checkUsageThresholdCount(bean, initialCount); System.out.println("INFO: Case finished successfully for " + bean.getName()); }
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()); }
protected void runTest() { MemoryPoolMXBean bean = btype.getMemoryPool(); long initialThresholdCount = bean.getUsageThresholdCount(); long initialUsage = bean.getUsage().getUsed(); bean.setUsageThreshold(initialUsage + 1 + CodeCacheUtils.MIN_ALLOCATION); long size = CodeCacheUtils.getHeaderSize(btype); CodeCacheUtils.WB.allocateCodeBlob(Math.max(0, CodeCacheUtils.MIN_ALLOCATION - size), btype.id); // a gc cycle triggers usage threshold recalculation CodeCacheUtils.WB.fullGC(); CodeCacheUtils.assertEQorGTE(btype, bean.getUsageThresholdCount(), initialThresholdCount, String.format("Usage threshold was hit: %d times for %s. " + "Threshold value: %d with current usage: %d", bean.getUsageThresholdCount(), bean.getName(), bean.getUsageThreshold(), bean.getUsage().getUsed())); System.out.println("INFO: Case finished successfully for " + bean.getName()); }
public static void main(String[] args) { List<MemoryPoolMXBean> pools = ManagementFactory.getMemoryPoolMXBeans(); boolean verified = false; for (MemoryPoolMXBean i : pools) { if ((i.getUsage().getMax() >= TWO_G) && i.isUsageThresholdSupported()) { i.setUsageThreshold(TWO_G); if(i.getUsageThreshold() != TWO_G) throw new RuntimeException("Usage threshold for" + " pool '" + i.getName() + "' is " + i.getUsageThreshold() + " and not equal to 2GB"); verified = true; } } System.out.println("Ability to use big heap thresholds has " + (verified ? "" : "NOT ") + "been verified"); }
@Test public void testNoCheckIntervalSpecifiedOneCondition() throws Exception { final MemoryPool memoryPool = mock(MemoryPool.class); final MemoryPoolMXBean memoryPoolBean = mock(MemoryPoolMXBean.class); final UsageThresholdCondition usageCondition = mock(UsageThresholdCondition.class); doReturn(Collections.singletonList(memoryPoolBean)).when(subject).getMemoryPoolMxBeans(); doReturn(memoryPool).when(jvm).getMemoryPool(memoryPoolBean); doReturn(usageCondition).when(memoryPool).toCondition(configuration); doReturn(percentageThresholdConfiguration(42d)).when(usageCondition) .getUsageThresholdConfiguration(); doReturn(-1L).when(configuration).getCheckIntervalInMillis(); subject.start(); verifyZeroInteractions(executor); verify(logger).error("One memory condition has been specified, but no check interval " + "has been provided; the heap-dump agent will not perform checks"); }
@Override public MemoryPool getMemoryPool(final MemoryPoolMXBean memoryPoolBean) { final MemoryPool.Type type = MemoryPool.Type.from(memoryPoolBean); boolean found = false; for (final MemoryPool.Type supportedType : getSupportedMemoryPoolTypes()) { if (type == supportedType) { found = true; break; } } if (!found) { throw new IllegalStateException( String.format("The memory pool type '%s' is not supported on the JVM type '%s'", type, this)); } return new MemoryPoolImpl(type, new Supplier<MemoryUsage>() { @Override public MemoryUsage get() { return memoryPoolBean.getUsage(); } }); }
@Override public void sense(final MetricRecorder.Context metricContext) { List<MemoryPoolMXBean> pools = ManagementFactory.getMemoryPoolMXBeans(); for (MemoryPoolMXBean mxBean : pools) { reportUsage(mxBean, metricContext); } }
private void reportMemoryPool() { for (final MemoryPoolMXBean pool : ManagementFactory.getMemoryPoolMXBeans()) { log.info("Memory Pool {} - type=\"{}\" memory-manager=\"{}\"", pool.getName(), pool.getType(), Joiner.on(',').join(pool.getMemoryManagerNames())); log.info("Memory Pool {} - Usage {}", pool.getName(), pool.getUsage()); log.info("Memory Pool {} - Collection Usage {}", pool.getName(), pool.getCollectionUsage()); log.info("Memory Pool {} - Peak Usage {}", pool.getName(), pool.getPeakUsage()); log.info("Memory Pool {} - Type {}", pool.getName(), pool.getPeakUsage()); } }
public JsonArray getMemoryPoolDetail() { List<MemoryPoolMXBean> mps = ManagementFactory.getMemoryPoolMXBeans(); JsonArray array = new JsonArray(); for (MemoryPoolMXBean mp : mps) { if (mp.getName().contains("Eden") || mp.getName().contains("Survivor") //win与linux上的不同,顾使用contains || mp.getName().contains("Tenured") || mp.getName().contains("Old")) { array.add(getMpJsonObject(mp)); } } return array; }
private JsonObject getMpJsonObject(MemoryPoolMXBean mp) { JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("name", mp.getName().replaceAll("PS ", "")); List<Long> array = new ArrayList<>(); JsonParser parser = new JsonParser(); array.add(mp.getCollectionUsage().getInit() / 1048576); array.add(mp.getCollectionUsage().getUsed() / 1048576); array.add(mp.getCollectionUsage().getCommitted() / 1048576); array.add(mp.getCollectionUsage().getMax() / 1048576); jsonObject.add("data", parser.parse(array.toString())); return jsonObject; }
public JvmGcMetrics(Iterable<Tag> tags) { for (MemoryPoolMXBean mbean : ManagementFactory.getMemoryPoolMXBeans()) { if (isYoungGenPool(mbean.getName())) youngGenPoolName = mbean.getName(); if (isOldGenPool(mbean.getName())) oldGenPoolName = mbean.getName(); } this.tags = tags; }
private static long getMemory(MemoryType type, MemoryValue memval) { long total = 0; List<MemoryPoolMXBean> memoryPoolBeans = ManagementFactory.getMemoryPoolMXBeans(); if (memoryPoolBeans.isEmpty()) { return -1; } for (Iterator<MemoryPoolMXBean> iterator = memoryPoolBeans.iterator(); iterator.hasNext();) { MemoryPoolMXBean memoryPoolMXBean = iterator.next(); if (memoryPoolMXBean.getType().equals(type)) { total += memval.getValue(memoryPoolMXBean); } } return total; }
private static List<MemPool> getPools() { List<MemoryPoolMXBean> poolMXBeans = ManagementFactory.getMemoryPoolMXBeans(); List<MemPool> result = new ArrayList<MemPool>(poolMXBeans.size() + 2); result.add(new MemPool("Heap", ManagementFactory.getMemoryMXBean().getHeapMemoryUsage())); result.add(new MemPool("Non-Heap", ManagementFactory.getMemoryMXBean().getNonHeapMemoryUsage())); for (MemoryPoolMXBean poolMXBean : poolMXBeans) { result.add(new MemPool(poolMXBean.getName(), poolMXBean.getUsage())); } return result; }
synchronized String[] getAllPoolNames() { if (poolNames == null) { List<MemoryPoolMXBean> pools = ManagementFactory.getMemoryPoolMXBeans(); poolNames = new String[pools.size()]; int i = 0; for (MemoryPoolMXBean m : pools) { poolNames[i++] = m.getName(); } } return poolNames; }
/** * Constructor for the "JvmMemPoolEntry" group. */ public JvmMemPoolEntryImpl(MemoryPoolMXBean mp, final int index) { this.pool=mp; this.jvmMemPoolIndex = index; this.entryMemoryTag = memoryTag + "." + index; this.entryPeakMemoryTag = peakMemoryTag + "." + index; this.entryCollectMemoryTag = collectMemoryTag + "." + index; }
public String[] getMemoryPoolNames() { MemoryPoolMXBean[] ps = getMemoryPools(); String[] names = new String[ps.length]; for (int i = 0; i < ps.length; i++) { names[i] = ps[i].getName(); } return names; }
private void initMemoryPools() { List<MemoryPoolMXBean> l = ManagementFactory.getMemoryPoolMXBeans(); for (MemoryPoolMXBean item : l) { if (item.isValid() && !mpMap.containsKey(item)) { mpMap.put(item, this.f.createStatistics(mpType, item.getName() + '-' + item.getType(), this.id)); } } }
/** * Returns the tenured pool MXBean or throws an IllegaleStateException if one couldn't be found. */ public static MemoryPoolMXBean getTenuredMemoryPoolMXBean() { if (tenuredMemoryPoolMXBean != null) { return tenuredMemoryPoolMXBean; } throw new IllegalStateException(LocalizedStrings.HeapMemoryMonitor_NO_POOL_FOUND_POOLS_0 .toLocalizedString(getAllMemoryPoolNames())); }
DumpMemories() { List<MemoryPoolMXBean> pools = ManagementFactory.getMemoryPoolMXBeans(); for (MemoryPoolMXBean p: pools) { System.out.println("Memory type="+p.getType()+" Memory usage="+p.getUsage()); } }
private int aggressiveRemoveObsoleteStatements(MemoryPoolMXBean tenuredPool, SortedMap<Long, StatementPosInPool> mapStatements, int nNbStatementForcedRemoved, int nNbSystemGCCall) { boolean bGCToDo = false; int nNbStatementRemoved = 0; Set<Map.Entry<Long, StatementPosInPool>> set = mapStatements.entrySet(); Iterator<Map.Entry<Long, StatementPosInPool>> iterMapEntry = set.iterator(); boolean bMemUsageTooMuch = true; while(iterMapEntry.hasNext() && bMemUsageTooMuch) { Map.Entry<Long, StatementPosInPool> mapEntry = iterMapEntry.next(); StatementPosInPool statementPosInPool = mapEntry.getValue(); boolean bRemoved = statementPosInPool.forceRemoveStatement(); if(bRemoved) { bGCToDo = true; nNbStatementRemoved++; if((nNbStatementRemoved % nNbStatementForcedRemoved) == 0) { tryForceGC(nNbSystemGCCall); bGCToDo = false; bMemUsageTooMuch = tenuredPool.isUsageThresholdExceeded(); } } } if(bGCToDo) { tryForceGC(nNbSystemGCCall); } return nNbStatementRemoved; }
public static void main(String[] args) { verifyThatMetaspaceMemoryManagerExists(); verifyMemoryPool(getMemoryPool("Metaspace"), isFlagDefined("MaxMetaspaceSize")); if (runsOn64bit()) { if (usesCompressedOops()) { MemoryPoolMXBean cksPool = getMemoryPool("Compressed Class Space"); verifyMemoryPool(cksPool, true); } } }
private static MemoryPoolMXBean getMemoryPool(String name) { List<MemoryPoolMXBean> pools = ManagementFactory.getMemoryPoolMXBeans(); for (MemoryPoolMXBean pool : pools) { if (pool.getName().equals(name)) { return pool; } } throw new RuntimeException("Expected to find a memory pool with name " + name); }
private static void verifyMemoryPool(MemoryPoolMXBean pool, boolean isMaxDefined) { MemoryUsage mu = pool.getUsage(); assertDefined(mu.getInit(), "init"); assertDefined(mu.getUsed(), "used"); assertDefined(mu.getCommitted(), "committed"); if (isMaxDefined) { assertDefined(mu.getMax(), "max"); } else { assertUndefined(mu.getMax(), "max"); } }