Java Code Examples for java.lang.management.ManagementFactory#getMemoryPoolMXBeans()

The following examples show how to use java.lang.management.ManagementFactory#getMemoryPoolMXBeans() . 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: HeapMonitorThread.java    From dremio-oss with Apache License 2.0 6 votes vote down vote 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());
    }
  }
}
 
Example 2
Source File: GarbageCollectorExtImpl.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private 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;
}
 
Example 3
Source File: MonitorMemory.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
@OnScheduled
public void onConfigured(final ConfigurationContext config) throws InitializationException {
    final String desiredMemoryPoolName = config.getProperty(MEMORY_POOL_PROPERTY).getValue();
    final String thresholdValue = config.getProperty(THRESHOLD_PROPERTY).getValue().trim();
    threshold = thresholdValue;

    final Long reportingIntervalValue = config.getProperty(REPORTING_INTERVAL).asTimePeriod(TimeUnit.MILLISECONDS);
    if (reportingIntervalValue == null) {
        reportingIntervalMillis = config.getSchedulingPeriod(TimeUnit.MILLISECONDS);
    } else {
        reportingIntervalMillis = reportingIntervalValue;
    }

    final List<MemoryPoolMXBean> memoryPoolBeans = ManagementFactory.getMemoryPoolMXBeans();
    for (int i = 0; i < memoryPoolBeans.size() && monitoredBean == null; i++) {
        MemoryPoolMXBean memoryPoolBean = memoryPoolBeans.get(i);
        String memoryPoolName = memoryPoolBean.getName();
        if (desiredMemoryPoolName.equals(memoryPoolName)) {
            monitoredBean = memoryPoolBean;
            if (memoryPoolBean.isCollectionUsageThresholdSupported()) {
                long calculatedThreshold;
                if (DATA_SIZE_PATTERN.matcher(thresholdValue).matches()) {
                    calculatedThreshold = DataUnit.parseDataSize(thresholdValue, DataUnit.B).longValue();
                } else {
                    final String percentage = thresholdValue.substring(0, thresholdValue.length() - 1);
                    final double pct = Double.parseDouble(percentage) / 100D;
                    calculatedThreshold = (long) (monitoredBean.getUsage().getMax() * pct);
                }
                monitoredBean.setUsageThreshold(calculatedThreshold);
            }
        }
    }

    if (monitoredBean == null) {
        throw new InitializationException("Found no JVM Memory Pool with name " + desiredMemoryPoolName + "; will not monitor Memory Pool");
    }
}
 
Example 4
Source File: LastGCInfo.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
private static void checkGcInfo(String name, GcInfo info) throws Exception {
    System.out.println("GC statistic for : " + name);
    System.out.print("GC #" + info.getId());
    System.out.print(" start:" + info.getStartTime());
    System.out.print(" end:" + info.getEndTime());
    System.out.println(" (" + info.getDuration() + "ms)");
    Map usage = info.getMemoryUsageBeforeGc();

    List pnames = new ArrayList();
    for (Iterator iter = usage.entrySet().iterator(); iter.hasNext(); ) {
        Map.Entry entry = (Map.Entry) iter.next();
        String poolname = (String) entry.getKey();
        pnames.add(poolname);
        MemoryUsage busage = (MemoryUsage) entry.getValue();
        MemoryUsage ausage = (MemoryUsage) info.getMemoryUsageAfterGc().get(poolname);
        if (ausage == null) {
            throw new RuntimeException("After Gc Memory does not exist" +
                " for " + poolname);
        }
        System.out.println("Usage for pool " + poolname);
        System.out.println("   Before GC: " + busage);
        System.out.println("   After GC: " + ausage);
    }

    // check if memory usage for all memory pools are returned
    List pools = ManagementFactory.getMemoryPoolMXBeans();
    for (Iterator iter = pools.iterator(); iter.hasNext(); ) {
        MemoryPoolMXBean p = (MemoryPoolMXBean) iter.next();
        if (!pnames.contains(p.getName())) {
            throw new RuntimeException("GcInfo does not contain " +
                "memory usage for pool " + p.getName());
        }
    }
}
 
Example 5
Source File: GarbageCollectorImpl.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
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;
}
 
Example 6
Source File: HeapMonitorThread.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
private void checkAndClawBackHeap() throws InterruptedException {
  // verify that at-least one of the pools has exceeded the collection threshold.
  boolean exceeded = false;
  for (MemoryPoolMXBean pool : ManagementFactory.getMemoryPoolMXBeans()) {
    if (!monitoredPools.containsKey(pool.getName())) {
      continue;
    }

    long thresholdExceededCount = pool.getCollectionUsageThresholdCount();
    if (monitoredPools.get(pool.getName()) < thresholdExceededCount) {
      monitoredPools.put(pool.getName(), thresholdExceededCount);
      exceeded = true;

      logger.info("heap usage " + pool.getUsage().getUsed() +
          " in pool " + pool.getName() +
          " exceeded threshold " + pool.getCollectionUsageThreshold() +
          " threshold_cnt " + pool.getCollectionUsageThresholdCount());
    }
  }
  if (exceeded) {
    strategy.clawBack();
  } else {
    logger.info("spurious wakeup");
  }

  // block for a while to let the cancel do it's work.
  Thread.sleep(1000);
}
 
Example 7
Source File: LastGCInfo.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
private static void checkGcInfo(String name, GcInfo info) throws Exception {
    System.out.println("GC statistic for : " + name);
    System.out.print("GC #" + info.getId());
    System.out.print(" start:" + info.getStartTime());
    System.out.print(" end:" + info.getEndTime());
    System.out.println(" (" + info.getDuration() + "ms)");
    Map usage = info.getMemoryUsageBeforeGc();

    List pnames = new ArrayList();
    for (Iterator iter = usage.entrySet().iterator(); iter.hasNext(); ) {
        Map.Entry entry = (Map.Entry) iter.next();
        String poolname = (String) entry.getKey();
        pnames.add(poolname);
        MemoryUsage busage = (MemoryUsage) entry.getValue();
        MemoryUsage ausage = (MemoryUsage) info.getMemoryUsageAfterGc().get(poolname);
        if (ausage == null) {
            throw new RuntimeException("After Gc Memory does not exist" +
                " for " + poolname);
        }
        System.out.println("Usage for pool " + poolname);
        System.out.println("   Before GC: " + busage);
        System.out.println("   After GC: " + ausage);
    }

    // check if memory usage for all memory pools are returned
    List pools = ManagementFactory.getMemoryPoolMXBeans();
    for (Iterator iter = pools.iterator(); iter.hasNext(); ) {
        MemoryPoolMXBean p = (MemoryPoolMXBean) iter.next();
        if (!pnames.contains(p.getName())) {
            throw new RuntimeException("GcInfo does not contain " +
                "memory usage for pool " + p.getName());
        }
    }
}
 
Example 8
Source File: DetailedMemoryMetricProvider.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
private Map<String, MemoryPoolMXBean> createMemoryPoolMap() {
    Map<String, MemoryPoolMXBean> memoryPoolMap = new HashMap<String, MemoryPoolMXBean>();
    List<MemoryPoolMXBean> memoryPools = ManagementFactory.getMemoryPoolMXBeans();
    for (MemoryPoolMXBean memoryPool : memoryPools) {
        memoryPoolMap.put(memoryPool.getName(), memoryPool);
    }
    return memoryPoolMap;
}
 
Example 9
Source File: JVMStateCapHandler.java    From uavstack with Apache License 2.0 5 votes vote down vote up
private void readHeapPoolUsage(MonitorElementInstance instance) {

        List<MemoryPoolMXBean> pmbList = ManagementFactory.getMemoryPoolMXBeans();

        /*for (MemoryPoolMXBean mpmb : pmbList) {

            String jvmMemPoolName = getHeapPoolName(mpmb.getName().trim());
    
            MemoryUsage mu = mpmb.getUsage();
    
            instance.setValue(jvmMemPoolName + "_use", mu.getUsed());
            instance.setValue(jvmMemPoolName + "_commit", mu.getCommitted());
            instance.setValue(jvmMemPoolName + "_max", mu.getMax());
            instance.setValue(jvmMemPoolName + "_init", mu.getInit());
        }*/
        
        Set<String> addedSet = new HashSet<String>();
        
        for (MemoryPoolMXBean mpmb : pmbList) {
    
            String jvmMemPoolName = getHeapPoolName(mpmb.getName().trim());
            MemoryUsage mu = mpmb.getUsage();
            
            if(addedSet.contains(jvmMemPoolName)) {
            
                instance.setValue(jvmMemPoolName + "_use", (Long)instance.getValue(jvmMemPoolName + "_use") + mu.getUsed());
                instance.setValue(jvmMemPoolName + "_commit", (Long)instance.getValue(jvmMemPoolName + "_commit") + mu.getCommitted());
                instance.setValue(jvmMemPoolName + "_max", (Long)instance.getValue(jvmMemPoolName + "_max") + mu.getMax());
                instance.setValue(jvmMemPoolName + "_init", (Long)instance.getValue(jvmMemPoolName + "_init") + mu.getInit());
            }else {
                
                addedSet.add(jvmMemPoolName);
                instance.setValue(jvmMemPoolName + "_use", mu.getUsed());
                instance.setValue(jvmMemPoolName + "_commit", mu.getCommitted());
                instance.setValue(jvmMemPoolName + "_max", mu.getMax());
                instance.setValue(jvmMemPoolName + "_init", mu.getInit());
            }
        }
    }
 
Example 10
Source File: GarbageCollectorImpl.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
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;
}
 
Example 11
Source File: MemoryLogger.java    From flink with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new memory logger that logs in the given interval and lives until the
 * given termination future completes.
 *
 * @param logger The logger to use for outputting the memory statistics.
 * @param interval The interval in which the thread logs.
 * @param monitored termination future for the system to whose life the thread is bound. The thread terminates
 *                  once the system terminates.
 */
public MemoryLogger(Logger logger, long interval, CompletableFuture<Void> monitored) {
	super("Memory Logger");
	setDaemon(true);
	setPriority(Thread.MIN_PRIORITY);
	
	this.logger = logger;
	this.interval = interval;
	this.monitored = monitored;

	this.memoryBean = ManagementFactory.getMemoryMXBean();
	this.poolBeans = ManagementFactory.getMemoryPoolMXBeans();
	this.gcBeans = ManagementFactory.getGarbageCollectorMXBeans();

	// The direct buffer pool bean needs to be accessed via the bean server
	MBeanServer beanServer = ManagementFactory.getPlatformMBeanServer();
	BufferPoolMXBean directBufferBean = null;
	try {
		directBufferBean = ManagementFactory.newPlatformMXBeanProxy(
				beanServer,
				"java.nio:type=BufferPool,name=direct",
				BufferPoolMXBean.class);
	}
	catch (Exception e) {
		logger.warn("Failed to initialize direct buffer pool bean.", e);
	}
	finally {
		this.directBufferBean = directBufferBean;
	}
}
 
Example 12
Source File: Pools.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private static MemoryPoolMXBean findPool(String poolName) {
    for (MemoryPoolMXBean pool : ManagementFactory.getMemoryPoolMXBeans()) {
        if (pool.getName().contains(poolName)) {
            return pool;
        }
    }
    return null;
}
 
Example 13
Source File: MemoryPoolDataProvider.java    From javametrics with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 14
Source File: JMXClient.java    From newblog with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 15
Source File: OperatingSystemInfoUtil.java    From Deta_Cache with Apache License 2.0 5 votes vote down vote up
/**
	 * Java ������е��ڴ��
	 */
	public static Map<String, Object> showMemoryPool(){
		Map<String, Object> map = new HashMap<>();
		List<MemoryPoolMXBean> mps = ManagementFactory.getMemoryPoolMXBeans();
		for(MemoryPoolMXBean mp : mps){
			Map<String, String> innerMap = new HashMap<>();
//			System.out.println("name:" + mp.getName());
//			System.out.println("CollectionUsage:" + mp.getCollectionUsage());
//			System.out.println("type:" + mp.getType());
			innerMap.put("CollectionUsage:", "" + mp.getCollectionUsage());
			innerMap.put("type:", "" + mp.getType());
			map.put(mp.getName(), innerMap);
		}
		return map;	
	}
 
Example 16
Source File: MemoryMonitor.java    From ns4_gear_watchdog with Apache License 2.0 5 votes vote down vote up
public static Report detect(Type selectType) {
    List<MemoryPoolMXBean> beans = ManagementFactory.getMemoryPoolMXBeans();
    Report report = new Report();
    for (MemoryPoolMXBean bean : beans) {
        if (selectType.equals(Type.All) || !filterPool(bean.getType(), selectType)) {
            report.addMemoryBeanInfo(bean);
        }
    }
    return report;
}
 
Example 17
Source File: MemoryUsageGaugeSet.java    From metrics with Apache License 2.0 4 votes vote down vote up
public MemoryUsageGaugeSet() {
    this(ManagementFactory.getMemoryMXBean(),
         ManagementFactory.getMemoryPoolMXBeans());
}
 
Example 18
Source File: Fawe.java    From FastAsyncWorldedit with GNU General Public License v3.0 4 votes vote down vote up
private void setupMemoryListener() {
    if (Settings.IMP.MAX_MEMORY_PERCENT < 1 || Settings.IMP.MAX_MEMORY_PERCENT > 99) {
        return;
    }
    try {
        final MemoryMXBean memBean = ManagementFactory.getMemoryMXBean();
        final NotificationEmitter ne = (NotificationEmitter) memBean;

        ne.addNotificationListener(new NotificationListener() {
            @Override
            public void handleNotification(final Notification notification, final Object handback) {
                final long heapSize = Runtime.getRuntime().totalMemory();
                final long heapMaxSize = Runtime.getRuntime().maxMemory();
                if (heapSize < heapMaxSize) {
                    return;
                }
                MemUtil.memoryLimitedTask();
            }
        }, null, null);

        final List<MemoryPoolMXBean> memPools = ManagementFactory.getMemoryPoolMXBeans();
        for (final MemoryPoolMXBean mp : memPools) {
            if (mp.isUsageThresholdSupported()) {
                final MemoryUsage mu = mp.getUsage();
                final long max = mu.getMax();
                if (max < 0) {
                    continue;
                }
                final long alert = (max * Settings.IMP.MAX_MEMORY_PERCENT) / 100;
                mp.setUsageThreshold(alert);
            }
        }
    } catch (Throwable e) {
        debug("====== MEMORY LISTENER ERROR ======");
        MainUtil.handleError(e, false);
        debug("===================================");
        debug("FAWE needs access to the JVM memory system:");
        debug(" - Change your Java security settings");
        debug(" - Disable this with `max-memory-percent: -1`");
        debug("===================================");
    }
}
 
Example 19
Source File: JvmMemPoolTableMetaImpl.java    From jdk8u_jdk with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Call ManagementFactory.getMemoryPoolMXBeans() to
 * load the raw data of this table.
 **/
protected List<MemoryPoolMXBean> loadRawDatas(Map<Object, Object> userData) {
    return ManagementFactory.getMemoryPoolMXBeans();
}
 
Example 20
Source File: JvmMemPoolTableMetaImpl.java    From jdk8u-dev-jdk with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Call ManagementFactory.getMemoryPoolMXBeans() to
 * load the raw data of this table.
 **/
protected List<MemoryPoolMXBean> loadRawDatas(Map<Object, Object> userData) {
    return ManagementFactory.getMemoryPoolMXBeans();
}