Example usage for java.lang.management MemoryPoolMXBean getUsage

List of usage examples for java.lang.management MemoryPoolMXBean getUsage

Introduction

In this page you can find the example usage for java.lang.management MemoryPoolMXBean getUsage.

Prototype

public MemoryUsage getUsage();

Source Link

Document

Returns an estimate of the memory usage of this memory pool.

Usage

From source file:VerboseGC.java

/**
 * Prints the verbose GC log to System.out to list the memory usage of all
 * memory pools as well as the GC statistics.
 *///w w w .j  a  v a2  s. c  o m
public void printVerboseGc() {
    System.out.print("Uptime: " + formatMillis(rmbean.getUptime()));
    for (GarbageCollectorMXBean gc : gcmbeans) {
        System.out.print(" [" + gc.getName() + ": ");
        System.out.print("Count=" + gc.getCollectionCount());
        System.out.print(" GCTime=" + formatMillis(gc.getCollectionTime()));
        System.out.print("]");
    }
    System.out.println();
    for (MemoryPoolMXBean p : pools) {
        System.out.print("  [" + p.getName() + ":");
        MemoryUsage u = p.getUsage();
        System.out.print(" Used=" + formatBytes(u.getUsed()));
        System.out.print(" Committed=" + formatBytes(u.getCommitted()));
        System.out.println("]");
    }
}

From source file:com.thoughtworks.go.server.service.support.ServerRuntimeInformationProvider.java

private void poolInfo(InformationStringBuilder builder) {
    builder.addSection("Memory pool information");

    List<MemoryPoolMXBean> memoryPoolMXBeans = ManagementFactory.getMemoryPoolMXBeans();
    for (MemoryPoolMXBean memoryPoolMXBean : memoryPoolMXBeans) {
        builder.append(String.format("Name: %s, Type: %s\n%s\n", memoryPoolMXBean.getName(),
                memoryPoolMXBean.getType(), format(memoryPoolMXBean.getUsage())));
    }//from w w  w .  j ava 2s.  c  o m
}

From source file:controllers.api.core.RootApiController.java

/**
 * Return some information regarding the memory status of the instance.
 *///from   ww w  . j ava 2s .  c  o  m
@ApiAuthentication(onlyRootKey = true)
public Result instanceMemoryStatus() {

    try {

        RootResponse response = new RootResponse();

        response.attributes = new HashMap<String, JsonNode>();
        List<MemoryPoolMXBean> mbeans = ManagementFactory.getMemoryPoolMXBeans();
        if (mbeans != null) {
            for (MemoryPoolMXBean mbean : mbeans) {
                System.out.println(mbean.getName());
                MemoryUsage memUsage = mbean.getUsage();
                HashMap<String, Long> memoryUsageAsMap = new HashMap<String, Long>();
                memoryUsageAsMap.put("init", memUsage.getInit());
                memoryUsageAsMap.put("max", memUsage.getMax());
                memoryUsageAsMap.put("committed", memUsage.getCommitted());
                memoryUsageAsMap.put("used", memUsage.getUsed());
                response.attributes.put(mbean.getName(), Json.toJson(memoryUsageAsMap));
            }
        }

        return getJsonSuccessResponse(response);

    } catch (Exception e) {

        return getJsonErrorResponse(new ApiError(500, "INTERNAL SERVER ERROR", e));

    }
}

From source file:edu.usu.sdl.openstorefront.web.rest.service.Application.java

@GET
@RequireAdmin//w  w w.  j a  va2 s.  c o m
@APIDescription("Gets the application system status")
@Produces({ MediaType.APPLICATION_JSON })
@DataType(ApplicationStatus.class)
@Path("/status")
public Response getApplicationStatus() {
    OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean();
    RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
    List<GarbageCollectorMXBean> garbageCollectorMXBeans = ManagementFactory.getGarbageCollectorMXBeans();
    MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean();
    List<MemoryPoolMXBean> memoryPoolMXBeans = ManagementFactory.getMemoryPoolMXBeans();
    ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();

    ApplicationStatus applicationStatus = new ApplicationStatus();
    applicationStatus.setApplicationVersion(PropertiesManager.getApplicationVersion());
    applicationStatus.setProcessorCount(operatingSystemMXBean.getAvailableProcessors());
    applicationStatus.setSystemLoad(operatingSystemMXBean.getSystemLoadAverage());
    applicationStatus.setSystemProperties(runtimeMXBean.getSystemProperties());

    applicationStatus.getHeapMemoryStatus().setName("Heap");
    applicationStatus.getHeapMemoryStatus().setDetails(memoryMXBean.getHeapMemoryUsage().toString());
    applicationStatus.getHeapMemoryStatus()
            .setInitKb(memoryMXBean.getHeapMemoryUsage().getInit() != 0
                    ? memoryMXBean.getHeapMemoryUsage().getInit() / 1024
                    : 0);
    applicationStatus.getHeapMemoryStatus()
            .setUsedKb(memoryMXBean.getHeapMemoryUsage().getUsed() != 0
                    ? memoryMXBean.getHeapMemoryUsage().getUsed() / 1024
                    : 0);
    applicationStatus.getHeapMemoryStatus()
            .setMaxKb(memoryMXBean.getHeapMemoryUsage().getMax() != 0
                    ? memoryMXBean.getHeapMemoryUsage().getMax() / 1024
                    : 0);
    applicationStatus.getHeapMemoryStatus()
            .setCommitedKb(memoryMXBean.getHeapMemoryUsage().getCommitted() != 0
                    ? memoryMXBean.getHeapMemoryUsage().getCommitted() / 1024
                    : 0);

    applicationStatus.getNonHeapMemoryStatus().setName("Non-Heap");
    applicationStatus.getNonHeapMemoryStatus().setDetails(memoryMXBean.getNonHeapMemoryUsage().toString());
    applicationStatus.getNonHeapMemoryStatus()
            .setInitKb(memoryMXBean.getNonHeapMemoryUsage().getInit() != 0
                    ? memoryMXBean.getNonHeapMemoryUsage().getInit() / 1024
                    : 0);
    applicationStatus.getNonHeapMemoryStatus()
            .setUsedKb(memoryMXBean.getNonHeapMemoryUsage().getUsed() != 0
                    ? memoryMXBean.getNonHeapMemoryUsage().getUsed() / 1024
                    : 0);
    applicationStatus.getNonHeapMemoryStatus()
            .setMaxKb(memoryMXBean.getNonHeapMemoryUsage().getMax() != 0
                    ? memoryMXBean.getNonHeapMemoryUsage().getMax() / 1024
                    : 0);
    applicationStatus.getNonHeapMemoryStatus()
            .setCommitedKb(memoryMXBean.getNonHeapMemoryUsage().getCommitted() != 0
                    ? memoryMXBean.getNonHeapMemoryUsage().getCommitted() / 1024
                    : 0);

    applicationStatus.setLiveThreadCount(threadMXBean.getThreadCount());
    applicationStatus.setTotalThreadCount(threadMXBean.getTotalStartedThreadCount());

    applicationStatus.setStartTime(new Date(runtimeMXBean.getStartTime()));
    applicationStatus.setUpTime(TimeUtil.millisToString(runtimeMXBean.getUptime()));

    for (GarbageCollectorMXBean garbageCollectorMXBean : garbageCollectorMXBeans) {
        applicationStatus.getGarbageCollectionInfos()
                .add(TimeUtil.millisToString(garbageCollectorMXBean.getCollectionTime()) + " - ("
                        + garbageCollectorMXBean.getCollectionCount() + ")");
    }

    for (MemoryPoolMXBean memoryPoolMXBean : memoryPoolMXBeans) {
        MemoryPoolStatus memoryPoolStatus = new MemoryPoolStatus();
        memoryPoolStatus.setName(memoryPoolMXBean.getName() + " - " + memoryPoolMXBean.getType());
        memoryPoolStatus.setDetails(memoryPoolMXBean.getUsage().toString());
        memoryPoolStatus.setInitKb(
                memoryPoolMXBean.getUsage().getInit() != 0 ? memoryPoolMXBean.getUsage().getInit() / 1024 : 0);
        memoryPoolStatus.setUsedKb(
                memoryPoolMXBean.getUsage().getUsed() != 0 ? memoryPoolMXBean.getUsage().getUsed() / 1024 : 0);
        memoryPoolStatus.setMaxKb(
                memoryPoolMXBean.getUsage().getMax() != 0 ? memoryPoolMXBean.getUsage().getMax() / 1024 : 0);
        memoryPoolStatus.setCommitedKb(memoryPoolMXBean.getUsage().getCommitted() != 0
                ? memoryPoolMXBean.getUsage().getCommitted() / 1024
                : 0);

        applicationStatus.getMemoryPools().add(memoryPoolStatus);
    }

    return sendSingleEntityResponse(applicationStatus);
}

From source file:com.eurelis.opencms.admin.systeminformation.CmsMemoryOverviewDialog.java

/**
 * Initializes the infos object.<p>
 *///from  w  w  w.j a v a 2  s . co  m
protected void initInfosObject() {

    com.sun.management.OperatingSystemMXBean sunOsBean = (com.sun.management.OperatingSystemMXBean) ManagementFactory
            .getOperatingSystemMXBean();
    java.lang.management.OperatingSystemMXBean osBean = ManagementFactory.getOperatingSystemMXBean();
    java.lang.management.ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
    java.lang.management.RuntimeMXBean runtimeBean = ManagementFactory.getRuntimeMXBean();
    java.lang.management.ClassLoadingMXBean classesBean = ManagementFactory.getClassLoadingMXBean();

    for (java.lang.management.MemoryPoolMXBean item : ManagementFactory.getMemoryPoolMXBeans()) {
        java.lang.management.MemoryUsage mu = item.getUsage();
        String name = item.getName();

        if (name.toLowerCase().contains("perm")) {
            setMemPermMax("" + mu.getMax());
            setMemPermTotal("" + mu.getCommitted());
            setMemPermUsed("" + mu.getUsed());
        } else if (name.toLowerCase().contains("old")) {
            setMemOldMax("" + mu.getMax());
            setMemOldTotal("" + mu.getCommitted());
            setMemOldUsed("" + mu.getUsed());
        } else if (name.toLowerCase().contains("eden")) {
            setMemEdenMax("" + mu.getMax());
            setMemEdenTotal("" + mu.getCommitted());
            setMemEdenUsed("" + mu.getUsed());
        } else if (name.toLowerCase().contains("survivor")) {
            setMemSurvivorMax("" + mu.getMax());
            setMemSurvivorTotal("" + mu.getCommitted());
            setMemSurvivorUsed("" + mu.getUsed());
        } else {
            //LOG.debug("MemoryPoolMXBean name = " + name.toLowerCase());
        }
    }

    Object o;
    if (CmsStringUtil.isEmpty(getParamAction())) {
        o = new CmsAdminSettings(getSession());
    } else {
        // this is not the initial call, get the job object from session
        o = getDialogObject();
    }
    if (!(o instanceof CmsAdminSettings)) {
        // create a new history settings handler object
        m_adminSettings = new CmsAdminSettings(getSession());
    } else {
        // reuse html import handler object stored in session
        m_adminSettings = (CmsAdminSettings) o;
    }

    setParamCloseLink(getJsp()
            .link("/system/workplace/views/admin/admin-main.jsp?path=/eurelis_system_information/memory.jsp"));
}

From source file:org.apache.hadoop.hive.llap.daemon.impl.LlapDaemon.java

public static long getTotalHeapSize() {
    // runtime.getMax() gives a very different number from the actual Xmx sizing.
    // you can iterate through the
    // http://docs.oracle.com/javase/7/docs/api/java/lang/management/MemoryPoolMXBean.html
    // from java.lang.management to figure this out, but the hard-coded params in the llap run.sh
    // result in 89% usable heap (-XX:NewRatio=8) + a survivor region which is technically not
    // in the usable space.

    long total = 0;
    for (MemoryPoolMXBean mp : ManagementFactory.getMemoryPoolMXBeans()) {
        long sz = mp.getUsage().getMax();
        if (mp.getName().contains("Survivor")) {
            sz *= 2; // there are 2 survivor spaces
        }/*from  ww w . ja  v a 2  s  .c  om*/
        if (mp.getType().equals(MemoryType.HEAP)) {
            total += sz;
        }
    }
    // round up to the next MB
    total += (total % (1024 * 1024));
    return total;
}

From source file:org.apache.pig.impl.util.SpillableMemoryManager.java

private SpillableMemoryManager() {
    ((NotificationEmitter) ManagementFactory.getMemoryMXBean()).addNotificationListener(this, null, null);
    List<MemoryPoolMXBean> mpbeans = ManagementFactory.getMemoryPoolMXBeans();
    long totalSize = 0;
    for (MemoryPoolMXBean pool : mpbeans) {
        log.debug("Found heap (" + pool.getName() + ") of type " + pool.getType());
        if (pool.getType() == MemoryType.HEAP) {
            long size = pool.getUsage().getMax();
            totalSize += size;//  w  ww. java  2s  .c  om
            // CMS Old Gen or "tenured" is the only heap that supports
            // setting usage threshold.
            if (pool.isUsageThresholdSupported()) {
                tenuredHeap = pool;
            }
        }
    }
    extraGCSpillSizeThreshold = (long) (totalSize * extraGCThresholdFraction);
    if (tenuredHeap == null) {
        throw new RuntimeException("Couldn't find heap");
    }

    configureMemoryThresholds(MEMORY_THRESHOLD_FRACTION_DEFAULT, COLLECTION_THRESHOLD_FRACTION_DEFAULT,
            UNUSED_MEMORY_THRESHOLD_DEFAULT);

}

From source file:org.craftercms.commons.monitoring.MemoryMonitor.java

/**
 * Query all register MemoryPools to get information and create a {@link MemoryMonitor} Pojo
 * @return List with all the memory usage stats.
 *///from  w ww.  j  a v a  2  s .  c o m
public static List<MemoryMonitor> getMemoryStats() {
    ArrayList<MemoryMonitor> memoryPoolInformation = new ArrayList<>();
    MemoryUsage heapMem = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage();
    memoryPoolInformation.add(new MemoryMonitor(HEAP_MEMORY, heapMem));
    MemoryUsage nonHeapMen = ManagementFactory.getMemoryMXBean().getNonHeapMemoryUsage();
    memoryPoolInformation.add(new MemoryMonitor(NON_HEAP_MEMORY, nonHeapMen));

    for (MemoryPoolMXBean memMXBean : ManagementFactory.getMemoryPoolMXBeans()) {
        memoryPoolInformation.add(new MemoryMonitor(memMXBean.getName(), memMXBean.getUsage()));
    }
    return Collections.unmodifiableList(memoryPoolInformation);
}

From source file:org.infoglue.deliver.applications.actions.ViewApplicationStateAction.java

private void addPermGenStatistics(List states) {
    Iterator iter1 = ManagementFactory.getMemoryPoolMXBeans().iterator();
    while (iter1.hasNext()) {
        MemoryPoolMXBean item = (MemoryPoolMXBean) iter1.next();
        long used = item.getUsage().getUsed() / 1024 / 1024;
        long max = item.getUsage().getMax() / 1024 / 1024;
        long usedDivided = used;
        long maxDivided = max;
        if (max > 100) {
            usedDivided = used / 10;/* www . j  av  a 2  s.  c  o  m*/
            maxDivided = max / 10;
        }

        states.add(getList("" + item.getName(), "" + used + " / " + max
                + "<div style='border: 1px solid #ccc; background-color: green; height: 10px; width: "
                + maxDivided + "px;'><div style='margin-top: 2px; background-color: red; height: 6px; width: "
                + usedDivided + "px;'></div></div>"));
    }

    long max = Runtime.getRuntime().maxMemory() / 1024 / 1024;
    long used = ((Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / 1024 / 1024);
    long usedDivided = used;
    long maxDivided = max;
    if (max > 100) {
        usedDivided = used / 10;
        maxDivided = max / 10;
    }

    states.add(getList("Heap summary", "" + used + " / " + max
            + "<div style='border: 1px solid #ccc; background-color: green; height: 10px; width: " + maxDivided
            + "px;'><div style='margin-top: 2px; background-color: red; height: 6px; width: " + usedDivided
            + "px;'></div></div>"));

}

From source file:org.jahia.bin.errors.ErrorFileDumper.java

public static void outputSystemInfo(PrintWriter strOut, boolean systemProperties, boolean environmentVariables,
        boolean jahiaSettings, boolean memory, boolean caches, boolean threads, boolean deadlocks,
        boolean loadAverage) {

    if (systemProperties) {
        // now let's output the system properties.
        strOut.println();//ww  w.j  a va 2s . c om
        strOut.println("System properties:");
        strOut.println("-------------------");
        Map<Object, Object> orderedProperties = new TreeMap<Object, Object>(System.getProperties());
        Iterator<Map.Entry<Object, Object>> entrySetIter = orderedProperties.entrySet().iterator();
        while (entrySetIter.hasNext()) {
            Map.Entry<Object, Object> curEntry = entrySetIter.next();
            String curPropertyName = (String) curEntry.getKey();
            String curPropertyValue = (String) curEntry.getValue();
            strOut.println("   " + curPropertyName + " : " + curPropertyValue);
        }
    }

    if (environmentVariables) {
        // now let's output the environment variables.
        strOut.println();
        strOut.println("Environment variables:");
        strOut.println("-------------------");
        Map<String, String> orderedProperties = new TreeMap<String, String>(System.getenv());
        Iterator<Map.Entry<String, String>> entrySetIter = orderedProperties.entrySet().iterator();
        while (entrySetIter.hasNext()) {
            Map.Entry<String, String> curEntry = entrySetIter.next();
            String curPropertyName = curEntry.getKey();
            String curPropertyValue = curEntry.getValue();
            strOut.println("   " + curPropertyName + " : " + curPropertyValue);
        }
    }

    if (jahiaSettings) {
        strOut.println();

        if (SettingsBean.getInstance() != null) {
            strOut.append("Server configuration (").append(Jahia.getFullProductVersion()).append(" - ")
                    .append(Jahia.getBuildDate()).append("):");
            strOut.println();
            strOut.println("---------------------");
            SettingsBean settings = SettingsBean.getInstance();
            Map<Object, Object> jahiaOrderedProperties = new TreeMap<Object, Object>(
                    settings.getPropertiesFile());
            Iterator<Map.Entry<Object, Object>> jahiaEntrySetIter = jahiaOrderedProperties.entrySet()
                    .iterator();
            while (jahiaEntrySetIter.hasNext()) {
                Map.Entry<Object, Object> curEntry = jahiaEntrySetIter.next();
                String curPropertyName = (String) curEntry.getKey();
                String curPropertyValue = null;
                if (curEntry.getValue() == null) {
                    curPropertyValue = null;
                } else if (curEntry.getValue() instanceof String) {
                    curPropertyValue = (String) curEntry.getValue();
                } else {
                    curPropertyValue = curEntry.getValue().toString();
                }
                if (curPropertyName.toLowerCase().indexOf("password") == -1
                        && (!"mail_server".equals(curPropertyName)
                                || !StringUtils.contains(curPropertyValue, "&password=")
                                        && !StringUtils.contains(curPropertyValue, "?password="))) {
                    strOut.println("   " + curPropertyName + " = " + curPropertyValue);
                }
            }
        }
    }

    if (memory) {
        MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean();
        MemoryUsage memoryUsage = memoryMXBean.getHeapMemoryUsage();
        printMemoryUsage(MemoryType.HEAP.toString(), memoryUsage, strOut);
        memoryUsage = memoryMXBean.getNonHeapMemoryUsage();
        printMemoryUsage(MemoryType.NON_HEAP.toString(), memoryUsage, strOut);

        strOut.println("--------------");
        strOut.println("Memory pool details");
        strOut.println("--------------");
        List<MemoryPoolMXBean> memoryPoolMXBeans = ManagementFactory.getMemoryPoolMXBeans();
        for (MemoryPoolMXBean bean : memoryPoolMXBeans) {
            printMemoryUsage("Memory Pool \"" + bean.getName() + "\" (" + bean.getType().toString() + ")",
                    bean.getUsage(), strOut);
        }
    }

    if (caches) {
        strOut.println();
        DecimalFormat percentFormat = new DecimalFormat("###.##");
        if (SpringContextSingleton.getInstance().isInitialized()
                && (ServicesRegistry.getInstance().getCacheService() != null)) {
            strOut.println("Cache status:");
            strOut.println("--------------");

            // non Ehcaches
            SortedSet<String> sortedCacheNames = new TreeSet<>(
                    ServicesRegistry.getInstance().getCacheService().getNames());
            for (String sortedCacheName : sortedCacheNames) {
                final Cache<Object, Object> objectCache = ServicesRegistry.getInstance().getCacheService()
                        .getCache(sortedCacheName);
                if (objectCache != null
                        && !(((Cache<?, ?>) objectCache).getCacheImplementation() instanceof EhCacheImpl)) {
                    String efficiencyStr = "0";
                    if (!Double.isNaN(objectCache.getCacheEfficiency())) {
                        efficiencyStr = percentFormat.format(objectCache.getCacheEfficiency());
                    }
                    strOut.println(sortedCacheName + ": size=" + objectCache.size() + ", successful hits="
                            + objectCache.getSuccessHits() + ", total hits=" + objectCache.getTotalHits()
                            + ", efficiency=" + efficiencyStr + "%");
                }
            }
        }

        // Ehcaches
        List<CacheManager> cacheManagers = CacheManager.ALL_CACHE_MANAGERS;
        for (CacheManager ehcacheManager : cacheManagers) {
            String[] ehcacheNames = ehcacheManager.getCacheNames();
            java.util.Arrays.sort(ehcacheNames);
            for (String ehcacheName : ehcacheNames) {
                Ehcache ehcache = ehcacheManager.getEhcache(ehcacheName);
                strOut.append(ehcacheName).append(": ");
                if (ehcache != null) {
                    StatisticsGateway ehcacheStats = ehcache.getStatistics();
                    String efficiencyStr = "0";
                    if (ehcacheStats.cacheHitCount() + ehcacheStats.cacheMissCount() > 0) {
                        efficiencyStr = percentFormat.format(ehcacheStats.cacheHitCount() * 100f
                                / (ehcacheStats.cacheHitCount() + ehcacheStats.cacheMissCount()));
                    }
                    strOut.append("size=" + ehcacheStats.getSize() + ", successful hits="
                            + ehcacheStats.cacheHitCount() + ", total hits="
                            + (ehcacheStats.cacheHitCount() + ehcacheStats.cacheMissCount()) + ", efficiency="
                            + efficiencyStr + "%");
                    strOut.println();
                }
            }
        }
    }

    ThreadMonitor threadMonitor = null;
    if (threads) {
        strOut.println();
        strOut.println("Thread status:");
        strOut.println("--------------");
        threadMonitor = ThreadMonitor.getInstance();
        threadMonitor.generateThreadInfo(strOut);
    }

    if (deadlocks) {
        strOut.println();
        strOut.println("Deadlock status:");
        threadMonitor = threadMonitor != null ? threadMonitor : ThreadMonitor.getInstance();
        ;
        String deadlock = threadMonitor.findDeadlock();
        strOut.println(deadlock != null ? deadlock : "none");
    }

    if (loadAverage) {
        strOut.println();
        strOut.println("Request load average:");
        strOut.println("---------------------");
        RequestLoadAverage info = RequestLoadAverage.getInstance();
        if (info != null) {
            strOut.println("Over one minute=" + info.getOneMinuteLoad() + " Over five minute="
                    + info.getFiveMinuteLoad() + " Over fifteen minute=" + info.getFifteenMinuteLoad());
        } else {
            strOut.println("not available");
        }
        strOut.println();
    }

    strOut.flush();
}