Java Code Examples for java.lang.management.MemoryPoolMXBean

The following examples show how to use java.lang.management.MemoryPoolMXBean. These examples are extracted from open source projects. 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 Project: jmxmon   Source File: MemoryPoolProxy.java    License: Apache License 2.0 6 votes vote down vote up
public MemoryPoolProxy(ProxyClient client, ObjectName poolName) throws java.io.IOException {
    this.client = client;
    this.objName = objName;
    this.pool = client.getMXBean(poolName, MemoryPoolMXBean.class);
    this.poolName = this.pool.getName();
    this.gcMBeans = new HashMap<ObjectName,Long>();
    this.lastGcInfo = null;

    String[] mgrNames = pool.getMemoryManagerNames();
    for (String name : mgrNames) {
        try {
            ObjectName mbeanName = new ObjectName(GARBAGE_COLLECTOR_MXBEAN_DOMAIN_TYPE +
                                                  ",name=" + name);
            if (client.isRegistered(mbeanName)) {
                gcMBeans.put(mbeanName, new Long(0));
            }
        } catch (Exception e) {
            throw new IllegalStateException(e);
        } 
   
    } 
}
 
Example 2
/**
 * 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;
}
 
Example 3
Source Project: mpush   Source File: JVMMemory.java    License: Apache License 2.0 6 votes vote down vote up
public JVMMemory() {
    memoryMXBean = ManagementFactory.getMemoryMXBean();
    List<MemoryPoolMXBean> list = ManagementFactory.getMemoryPoolMXBeans();
    for (MemoryPoolMXBean item : list) {
        String name = item.getName();
        if (permGenName.contains(name)) {
            permGenMxBean = item;
        } else if (oldGenName.contains(name)) {
            oldGenMxBean = item;
        } else if (edenSpaceName.contains(name)) {
            edenSpaceMxBean = item;
        } else if (psSurvivorName.contains(name)) {
            pSSurvivorSpaceMxBean = item;
        }
    }
}
 
Example 4
Source Project: kfs   Source File: MemoryMonitor.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
public MemoryMonitor() {
    LOG.info("initializing");
    this.springContextId = "Unknown";
    ManagementFactory.getThreadMXBean().setThreadContentionMonitoringEnabled(true);
    ManagementFactory.getThreadMXBean().setThreadCpuTimeEnabled(true);
    lowMemoryListener = new NotificationListener() {
        public void handleNotification(Notification n, Object hb) {
            if (n.getType().equals(MemoryNotificationInfo.MEMORY_THRESHOLD_EXCEEDED)) {
                Map<String, String> memoryUsageStatistics = new HashMap<String, String>();
                memoryUsageStatistics.put("MemoryMXBean: " + MemoryType.HEAP, ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().toString());
                memoryUsageStatistics.put("MemoryMXBean:" + MemoryType.NON_HEAP, ManagementFactory.getMemoryMXBean().getNonHeapMemoryUsage().toString());
                for (MemoryPoolMXBean pool : ManagementFactory.getMemoryPoolMXBeans()) {
                    memoryUsageStatistics.put("MemoryPoolMXBean: " + pool.getType(), pool.getUsage().toString());
                }
                for (Listener listener : listeners) {
                    listener.memoryUsageLow(springContextId, memoryUsageStatistics, Arrays.toString(ManagementFactory.getThreadMXBean().findMonitorDeadlockedThreads()));
                }
            }
        }
    };
    ((NotificationEmitter) ManagementFactory.getMemoryMXBean()).addNotificationListener(lowMemoryListener, null, null);
}
 
Example 5
Source Project: fqueue   Source File: JVMMonitor.java    License: Apache License 2.0 6 votes vote down vote up
public static Map<String, MemoryUsage> getMemoryPoolCollectionUsage() {
    Map<String, MemoryUsage> gcMemory = new HashMap<String, MemoryUsage>();
    for (MemoryPoolMXBean memoryPoolMXBean : memoryPoolMXBeans) {
        String name = memoryPoolMXBean.getName();
        if (edenSpace.contains(name)) {
            gcMemory.put("eden", memoryPoolMXBean.getCollectionUsage());
        } else if (survivorSpace.contains(name)) {
            gcMemory.put("survivor", memoryPoolMXBean.getCollectionUsage());
        } else if (oldSpace.contains(name)) {
            gcMemory.put("old", memoryPoolMXBean.getCollectionUsage());
        } else if (permSpace.contains(name)) {
            gcMemory.put("perm", memoryPoolMXBean.getCollectionUsage());
        } else if (codeCacheSpace.contains(name)) {
            gcMemory.put("codeCache", memoryPoolMXBean.getCollectionUsage());
        }

    }
    return gcMemory;
}
 
Example 6
Source Project: aws-sdk-java-v2   Source File: StabilityTestRunner.java    License: Apache License 2.0 6 votes vote down vote up
private double calculateHeapMemoryAfterGCUsage() {
    List<MemoryPoolMXBean> memoryPoolMXBeans = ManagementFactory.getMemoryPoolMXBeans();

    long used = 0, max = 0;

    for (MemoryPoolMXBean memoryPoolMXBean : memoryPoolMXBeans) {
        String name = memoryPoolMXBean.getName();

        if (!name.contains("Eden")) {
            if (memoryPoolMXBean.getType().equals(HEAP)) {
                MemoryUsage memoryUsage = memoryPoolMXBean.getCollectionUsage();
                used += memoryUsage.getUsed();
                max += memoryUsage.getMax() == -1 ? 0 : memoryUsage.getMax();
            }
        }
    }

    return used / (double) max;
}
 
Example 7
Source Project: openjdk-jdk9   Source File: GarbageProducer.java    License: GNU General Public License v2.0 6 votes vote down vote up
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;
}
 
Example 8
@Override
public Stream<MetricFamily> collect() {
    final Stream.Builder<NumericMetric> initialBytesMetrics = Stream.builder();
    final Stream.Builder<NumericMetric> usedBytesMetrics = Stream.builder();
    final Stream.Builder<NumericMetric> committedBytesMetrics = Stream.builder();
    final Stream.Builder<NumericMetric> maximumBytesMetrics = Stream.builder();

    for (final Map.Entry<Labels, MemoryPoolMXBean> entry : labeledMemoryPoolMXBeans.entrySet()) {
        final Labels labels = entry.getKey();
        final MemoryPoolMXBean memoryPoolMXBean = entry.getValue();

        final MemoryUsage usage = memoryPoolMXBean.getUsage();

        initialBytesMetrics.add(new NumericMetric(labels, neg1ToNaN(usage.getInit())));
        usedBytesMetrics.add(new NumericMetric(labels, usage.getUsed()));
        committedBytesMetrics.add(new NumericMetric(labels, usage.getCommitted()));
        maximumBytesMetrics.add(new NumericMetric(labels, neg1ToNaN(usage.getMax())));
    }

    return Stream.of(
            new GaugeMetricFamily("cassandra_jvm_memory_pool_initial_bytes", "Initial size of the memory pool.", initialBytesMetrics.build()),
            new GaugeMetricFamily("cassandra_jvm_memory_pool_used_bytes", "Current memory pool usage.", usedBytesMetrics.build()),
            new GaugeMetricFamily("cassandra_jvm_memory_pool_committed_bytes", null, committedBytesMetrics.build()),
            new GaugeMetricFamily("cassandra_jvm_memory_pool_maximum_bytes", "Maximum size of the memory pool.", maximumBytesMetrics.build())
    );
}
 
Example 9
Source Project: fqueue   Source File: JVMMonitor.java    License: Apache License 2.0 6 votes vote down vote up
public static Map<String, MemoryUsage> getMemoryPoolPeakUsage() {
    Map<String, MemoryUsage> gcMemory = new HashMap<String, MemoryUsage>();
    for (MemoryPoolMXBean memoryPoolMXBean : memoryPoolMXBeans) {
        String name = memoryPoolMXBean.getName();
        if (edenSpace.contains(name)) {
            gcMemory.put("eden", memoryPoolMXBean.getPeakUsage());
        } else if (survivorSpace.contains(name)) {
            gcMemory.put("survivor", memoryPoolMXBean.getPeakUsage());
        } else if (oldSpace.contains(name)) {
            gcMemory.put("old", memoryPoolMXBean.getPeakUsage());
        } else if (permSpace.contains(name)) {
            gcMemory.put("perm", memoryPoolMXBean.getPeakUsage());
        } else if (codeCacheSpace.contains(name)) {
            gcMemory.put("codeCache", memoryPoolMXBean.getPeakUsage());
        }

    }
    return gcMemory;
}
 
Example 10
/**
 * 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;
}
 
Example 11
/**
 * 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;
}
 
Example 12
Source Project: vjtools   Source File: JmxMemoryPoolManager.java    License: Apache License 2.0 6 votes vote down vote up
public JmxMemoryPoolManager(MBeanServerConnection connection) throws IOException {
	List<MemoryPoolMXBean> memoryPoolMXBeans = ManagementFactory.getPlatformMXBeans(connection,
			MemoryPoolMXBean.class);
	for (MemoryPoolMXBean memoryPool : memoryPoolMXBeans) {
		String name = memoryPool.getName().trim();
		String lowerCaseName = name.toLowerCase();
		if (lowerCaseName.contains(SURVIVOR)) {
			survivorMemoryPool = memoryPool;
		} else if (lowerCaseName.contains(EDEN)) {
			edenMemoryPool = memoryPool;
		} else if (lowerCaseName.contains(OLD) || lowerCaseName.contains(TENURED)) {
			oldMemoryPool = memoryPool;
		} else if (lowerCaseName.contains(PERM) || lowerCaseName.contains(METASPACE)) {
			permMemoryPool = memoryPool;
		} else if (lowerCaseName.contains(CODE_CACHE)) {
			codeCacheMemoryPool = memoryPool;
		} else if (lowerCaseName.contains(COMPRESSED_CLASS_SPACE)) {
			compressedClassSpaceMemoryPool = memoryPool;
		}
	}
}
 
Example 13
/**
 * 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;
}
 
Example 14
/**
 * 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;
}
 
Example 15
Source Project: ns4_gear_watchdog   Source File: MemoryMonitor.java    License: Apache License 2.0 5 votes vote down vote up
void addMemoryBeanInfo(MemoryPoolMXBean bean) {
    Map<String, Map<String, Object>> memoryMap = bean.getType().equals(MemoryType.HEAP) ? heapMap : nonHeapMap;
    Map<String, Object> beanMap = memoryMap.get(bean.getName());
    if (beanMap == null) {
        beanMap = new HashMap<>();
        memoryMap.put(bean.getName(), beanMap);
    }
    addUsage(beanMap, bean.getUsage());
    addPeak(beanMap, bean.getPeakUsage());
}
 
Example 16
private MemoryUsage getCodeCacheUsage() {
    List<MemoryPoolMXBean> memoryPoolMXBeans = ManagementFactory.getMemoryPoolMXBeans();
    for (MemoryPoolMXBean memoryPoolMXBean : memoryPoolMXBeans) {
        if (MEMORY_POOL_CODE_CACHE.equals(memoryPoolMXBean.getName())) {
            return memoryPoolMXBean.getUsage();
        }
    }
    return null;
}
 
Example 17
Source Project: opentelemetry-java   Source File: MemoryPools.java    License: Apache License 2.0 5 votes vote down vote up
/** Export only the "pool" metric. */
public void exportMemoryPoolMetric() {
  final LongUpDownSumObserver poolMetric =
      this.meter
          .longUpDownSumObserverBuilder("pool")
          .setDescription("Bytes of a given JVM memory pool.")
          .setUnit("By")
          .build();
  final List<Labels> usedLabelSets = new ArrayList<>(poolBeans.size());
  final List<Labels> committedLabelSets = new ArrayList<>(poolBeans.size());
  final List<Labels> maxLabelSets = new ArrayList<>(poolBeans.size());
  for (final MemoryPoolMXBean pool : poolBeans) {
    usedLabelSets.add(Labels.of(TYPE_LABEL_KEY, USED, POOL_LABEL_KEY, pool.getName()));
    committedLabelSets.add(Labels.of(TYPE_LABEL_KEY, COMMITTED, POOL_LABEL_KEY, pool.getName()));
    maxLabelSets.add(Labels.of(TYPE_LABEL_KEY, MAX, POOL_LABEL_KEY, pool.getName()));
  }
  poolMetric.setCallback(
      new Callback<LongResult>() {
        @Override
        public void update(LongResult resultLongObserver) {
          for (int i = 0; i < poolBeans.size(); i++) {
            MemoryUsage poolUsage = poolBeans.get(i).getUsage();
            resultLongObserver.observe(poolUsage.getUsed(), usedLabelSets.get(i));
            resultLongObserver.observe(poolUsage.getCommitted(), committedLabelSets.get(i));
            // TODO: Decide if max is needed or not. May be derived with some approximation from
            //  max(used).
            resultLongObserver.observe(poolUsage.getMax(), maxLabelSets.get(i));
          }
        }
      });
}
 
Example 18
Source Project: uavstack   Source File: JVMStateCapHandler.java    License: 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 19
Source Project: perfmon-agent   Source File: MemoryPoolDataProviderTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Test of getMXBeanClass method, of class MemoryPoolDataProvider.
 */
public void testGetMXBeanClass() throws Exception {
    System.out.println("getMXBeanClass");
    MemoryPoolDataProvider instance = new MemoryPoolDataProvider(new EmulatorMBeanServerConnection(), false, MemoryPoolDataProvider.TYPE_COMMITTED);
    Class expResult = MemoryPoolMXBean.class;
    Class result = instance.getMXBeanClass();
    assertEquals(expResult, result);
}
 
Example 20
Source Project: javamelody   Source File: MemoryInformations.java    License: Apache License 2.0 5 votes vote down vote up
private static MemoryPoolMXBean getPermGenMemoryPool() {
	for (final MemoryPoolMXBean memoryPool : ManagementFactory.getMemoryPoolMXBeans()) {
		// name est "Perm Gen" ou "PS Perm Gen" (32 vs 64 bits ?)
		if (memoryPool.getName().endsWith("Perm Gen")) {
			return memoryPool;
		}
	}
	return null;
}
 
Example 21
Source Project: easybuggy   Source File: MemoryLeakServlet.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    StringBuilder bodyHtml = new StringBuilder();
    Locale locale = req.getLocale();
    try {
        toDoRemove();
        
        List<MemoryPoolMXBean> memoryPoolMXBeans = ManagementFactory.getMemoryPoolMXBeans();
        for (MemoryPoolMXBean memoryPoolMXBean : memoryPoolMXBeans) {
            if (MemoryType.HEAP.equals(memoryPoolMXBean.getType())) {
                bodyHtml.append("<p>" + memoryPoolMXBean.getName() + "</p>");
                bodyHtml.append("<table class=\"table table-striped table-bordered table-hover\" style=\"font-size:small;\">");
                bodyHtml.append("<tr><th></th>");
                bodyHtml.append("<th width=\"18%\">" + getMsg("label.memory.init", locale) + "</th>");
                bodyHtml.append("<th width=\"18%\">" + getMsg("label.memory.used", locale) + "</th>");
                bodyHtml.append("<th width=\"18%\">" + getMsg("label.memory.committed", locale) + "</th>");
                bodyHtml.append("<th width=\"18%\">" + getMsg("label.memory.max", locale) + "</th></tr>");
                writeUsageRow(bodyHtml, memoryPoolMXBean.getUsage(), getMsg("label.memory.usage", locale));
                writeUsageRow(bodyHtml, memoryPoolMXBean.getPeakUsage(), getMsg("label.memory.peak.usage", locale));
                writeUsageRow(bodyHtml, memoryPoolMXBean.getCollectionUsage(), getMsg("label.memory.collection.usage", locale));
                bodyHtml.append("</table>");
            }
        }
        bodyHtml.append(getInfoMsg("msg.note.memoryleak", req.getLocale()));

    } catch (Exception e) {
        log.error("Exception occurs: ", e);
        bodyHtml.append(getErrMsg("msg.unknown.exception.occur", new String[] { e.getMessage() }, locale));
    } finally {
        responseToClient(req, res, getMsg("title.memoryleak.page", locale), bodyHtml.toString());
    }
}
 
Example 22
Source Project: jdk8u-jdk   Source File: MemoryManagerImpl.java    License: GNU General Public License v2.0 5 votes vote down vote up
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;
}
 
Example 23
Source Project: hottub   Source File: MemoryManagerImpl.java    License: GNU General Public License v2.0 5 votes vote down vote up
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;
}
 
Example 24
Source Project: jdk8u_jdk   Source File: LastGCInfo.java    License: 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 25
private void fillWithSize(long size, List<Long> blobs, MemoryPoolMXBean bean) {
    long blob;
    /* Don't fill too much to have space for adapters. So, stop after crossing 95% and
       don't allocate in case we'll cross 97% on next allocation. We can hit situation
       like 94% -> (1 allocation) -> 100% otherwise. So, check if
       <Usage + allocatedSize> is less than 97%, then allocate in case it is, then, stop
       further allocations with given size in case <Usage> more than 95% */
    while (((double) bean.getUsage().getUsed() + size <= (CACHE_USAGE_COEF + 0.02d)  * maxSize)
            && (blob = CodeCacheUtils.WB.allocateCodeBlob(size, btype.id)) != 0L
            && ((double) bean.getUsage().getUsed() <= CACHE_USAGE_COEF * maxSize)) {
        blobs.add(blob);
    }
}
 
Example 26
Source Project: spectator   Source File: MemoryPoolMeter.java    License: Apache License 2.0 5 votes vote down vote up
@Override public Iterable<Measurement> measure() {
  final long timestamp = clock.wallTime();
  final MemoryPoolMXBean mbean = ref.get();
  final List<Measurement> ms = new ArrayList<>();
  if (mbean != null) {
    final String typeKey = "memtype";
    final String type = mbean.getType().name();

    final MemoryUsage usage = mbean.getUsage();
    ms.add(new Measurement(usedId.withTag(typeKey, type), timestamp, usage.getUsed()));
    ms.add(new Measurement(committedId.withTag(typeKey, type), timestamp, usage.getCommitted()));
    ms.add(new Measurement(maxId.withTag(typeKey, type), timestamp, usage.getMax()));
  }
  return ms;
}
 
Example 27
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;
}
 
Example 28
Source Project: swage   Source File: MemoryPoolSensor.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void sense(final MetricContext metricContext)
{
    List<MemoryPoolMXBean> pools = ManagementFactory.getMemoryPoolMXBeans();

    for (MemoryPoolMXBean mxBean : pools) {
        reportUsage(mxBean, metricContext);
    }

}
 
Example 29
private static boolean canAllocate(double size, long maxSize, MemoryPoolMXBean bean) {
    // Don't fill too much to have space for adapters. So, stop after crossing 95% and
    // don't allocate in case we'll cross 97% on next allocation.
    double used = bean.getUsage().getUsed();
    return (used <= CACHE_USAGE_COEF * maxSize) &&
           (used + size <= (CACHE_USAGE_COEF + 0.02d)  * maxSize);
}
 
Example 30
Source Project: TencentKona-8   Source File: LastGCInfo.java    License: 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());
        }
    }
}