Example usage for java.lang.management MemoryUsage getMax

List of usage examples for java.lang.management MemoryUsage getMax

Introduction

In this page you can find the example usage for java.lang.management MemoryUsage getMax.

Prototype

public long getMax() 

Source Link

Document

Returns the maximum amount of memory in bytes that can be used for memory management.

Usage

From source file:com.snowstore.mercury.core.metric.SystemPublicMetrics.java

/**
 * Add JVM heap metrics.//w w  w  .  j  a  v a  2s.c o  m
 * 
 * @param result
 *            the result
 */
protected void addNoHeapMetrics(Collection<Metric<?>> result) {
    MemoryUsage memoryUsage = ManagementFactory.getMemoryMXBean().getNonHeapMemoryUsage();
    result.add(new Metric<Long>("noheap.committed", memoryUsage.getCommitted() / 1024));
    result.add(new Metric<Long>("noheap.init", memoryUsage.getInit() / 1024));
    result.add(new Metric<Long>("noheap.used", memoryUsage.getUsed() / 1024));
    result.add(new Metric<Long>("noheap", memoryUsage.getMax() / 1024));
}

From source file:org.eclipse.gyrex.cloud.internal.NodeMetricsReporter.java

@Override
protected IStatus run(final IProgressMonitor monitor) {
    if (monitor.isCanceled()) {
        return Status.CANCEL_STATUS;
    }//from ww  w . ja va 2 s . c  om

    try {
        final Properties metrics = new Properties() {
            private static final long serialVersionUID = 1L;

            @Override
            public synchronized Enumeration<Object> keys() {
                return Collections.enumeration(keySet());
            }

            @Override
            public Set<Object> keySet() {
                return new TreeSet<Object>(super.keySet());
            }
        };
        final OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean();
        metrics.setProperty("os.availableProcessors",
                String.valueOf(operatingSystemMXBean.getAvailableProcessors()));
        metrics.setProperty("os.systemLoadAverage",
                String.valueOf(operatingSystemMXBean.getSystemLoadAverage()));
        metrics.setProperty("os.committedVirtualMemorySize",
                getUsingReflection(operatingSystemMXBean, "getCommittedVirtualMemorySize"));
        metrics.setProperty("os.totalSwapSpaceSize",
                getUsingReflection(operatingSystemMXBean, "getTotalSwapSpaceSize"));
        metrics.setProperty("os.freeSwapSpaceSize",
                getUsingReflection(operatingSystemMXBean, "getFreeSwapSpaceSize"));
        metrics.setProperty("os.processCpuTime",
                getUsingReflection(operatingSystemMXBean, "getProcessCpuTime"));
        metrics.setProperty("os.freePhysicalMemorySize",
                getUsingReflection(operatingSystemMXBean, "getFreePhysicalMemorySize"));
        metrics.setProperty("os.totalPhysicalMemorySize",
                getUsingReflection(operatingSystemMXBean, "getTotalPhysicalMemorySize"));
        metrics.setProperty("os.openFileDescriptorCount",
                getUsingReflection(operatingSystemMXBean, "getOpenFileDescriptorCount"));
        metrics.setProperty("os.maxFileDescriptorCount",
                getUsingReflection(operatingSystemMXBean, "getMaxFileDescriptorCount"));

        final MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean();
        final MemoryUsage heapMemoryUsage = memoryMXBean.getHeapMemoryUsage();
        metrics.setProperty("heap.used", String.valueOf(heapMemoryUsage.getUsed()));
        metrics.setProperty("heap.committed", String.valueOf(heapMemoryUsage.getCommitted()));
        metrics.setProperty("heap.max", String.valueOf(heapMemoryUsage.getMax()));
        metrics.setProperty("heap.init", String.valueOf(heapMemoryUsage.getInit()));
        final MemoryUsage nonHeapMemoryUsage = memoryMXBean.getNonHeapMemoryUsage();
        metrics.setProperty("nonHeap.used", String.valueOf(nonHeapMemoryUsage.getUsed()));
        metrics.setProperty("nonHeap.committed", String.valueOf(nonHeapMemoryUsage.getCommitted()));
        metrics.setProperty("nonHeap.max", String.valueOf(nonHeapMemoryUsage.getMax()));
        metrics.setProperty("nonHeap.init", String.valueOf(nonHeapMemoryUsage.getInit()));

        final ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
        metrics.setProperty("thread.count", String.valueOf(threadMXBean.getThreadCount()));
        metrics.setProperty("thread.peak", String.valueOf(threadMXBean.getPeakThreadCount()));
        metrics.setProperty("thread.totalStarted", String.valueOf(threadMXBean.getTotalStartedThreadCount()));

        final RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
        metrics.setProperty("uptime", String.valueOf(runtimeMXBean.getUptime()));

        final ByteArrayOutputStream out = new ByteArrayOutputStream();
        final NodeInfo nodeInfo = CloudState.getNodeInfo();
        metrics.store(out, String.valueOf(nodeInfo));
        ZooKeeperGate.get().writeRecord(IZooKeeperLayout.PATH_NODES_METRICS.append(nodeInfo.getNodeId()),
                CreateMode.PERSISTENT, out.toByteArray());
        if (CloudDebug.nodeMetrics) {
            LOG.debug("Node metrics reported successfully.{}{}", SystemUtils.LINE_SEPARATOR,
                    new String(out.toByteArray(), CharEncoding.ISO_8859_1));
        }
    } catch (final Exception e) {
        LOG.warn("Failed to update node metrics. {}", e.getMessage());
    } finally {
        // reschedule
        schedule(DELAY);
    }

    return Status.OK_STATUS;
}

From source file:org.artifactory.webapp.wicket.page.config.advanced.SystemInfoPage.java

/**
 * Return a formatted string of the system info to display
 *
 * @return//from   ww w  .  j a  va2s  .  c  o m
 */
private String collectSystemInfo() {
    StringBuilder infoBuilder = new StringBuilder();

    StorageProperties storageProperties = ContextHelper.get().beanForType(StorageProperties.class);
    infoBuilder.append("Storage Info:").append("\n");
    addInfo(infoBuilder, "Database Type", storageProperties.getDbType().toString());
    BinaryProviderType binariesStorageType = storageProperties.getBinariesStorageType();
    addInfo(infoBuilder, "Storage Type", binariesStorageType.toString());
    if (BinaryProviderType.S3 == binariesStorageType) {
        // S3 properties
        addInfo(infoBuilder, "s3.bucket.name", storageProperties.getS3BucketName());
        addInfo(infoBuilder, "s3.bucket.path", storageProperties.getS3BucketPath());
        addInfo(infoBuilder, "s3.endpoint", storageProperties.getS3Entpoint());
        // Retry properties
        addInfo(infoBuilder, "retry.max.retries.number",
                Integer.toString(storageProperties.getMaxRetriesNumber()));
        addInfo(infoBuilder, "retry.delay.between.retries",
                Integer.toString(storageProperties.getDelayBetweenRetries()));
        // Eventually persisted properties
        addInfo(infoBuilder, "eventually.persisted.max.number.of.threads",
                Integer.toString(storageProperties.getEventuallyPersistedMaxNumberOfThread()));
        addInfo(infoBuilder, "eventually.persisted.timeout",
                Integer.toString(storageProperties.getEventuallyPersistedTimeOut()));
        addInfo(infoBuilder, "eventually.dispatcher.sleep.time",
                Long.toString(storageProperties.getEventuallyPersistedDispatcherSleepTime()));
    }

    infoBuilder.append("\n").append("System Properties:").append("\n");
    Properties properties = System.getProperties();
    //// add Artifactory version to the properties, will be alphabetically sorted later.
    properties.setProperty(ConstantValues.artifactoryVersion.getPropertyName(),
            ConstantValues.artifactoryVersion.getString());
    AddonsManager addonsManager = ContextHelper.get().beanForType(AddonsManager.class);
    addInfo(infoBuilder, "artifactory.running.mode", addonsManager.getArtifactoryRunningMode().name());
    addInfo(infoBuilder, "artifactory.running.state", ContextHelper.get().isOffline() ? "Offline" : "Online");
    addFromProperties(infoBuilder, properties);
    addHaProperties(infoBuilder);
    infoBuilder.append("\n").append("General JVM Info:").append("\n");
    OperatingSystemMXBean systemBean = ManagementFactory.getOperatingSystemMXBean();
    addInfo(infoBuilder, "Available Processors", Integer.toString(systemBean.getAvailableProcessors()));

    MemoryMXBean memoryBean = ManagementFactory.getMemoryMXBean();
    MemoryUsage heapMemoryUsage = memoryBean.getHeapMemoryUsage();

    addInfo(infoBuilder, "Heap Memory Usage-Committed", Long.toString(heapMemoryUsage.getCommitted()));
    addInfo(infoBuilder, "Heap Memory Usage-Init", Long.toString(heapMemoryUsage.getInit()));
    addInfo(infoBuilder, "Heap Memory Usage-Max", Long.toString(heapMemoryUsage.getMax()));
    addInfo(infoBuilder, "Heap Memory Usage-Used", Long.toString(heapMemoryUsage.getUsed()));

    MemoryUsage nonHeapMemoryUsage = memoryBean.getNonHeapMemoryUsage();
    addInfo(infoBuilder, "Non-Heap Memory Usage-Committed", Long.toString(nonHeapMemoryUsage.getCommitted()));
    addInfo(infoBuilder, "Non-Heap Memory Usage-Init", Long.toString(nonHeapMemoryUsage.getInit()));
    addInfo(infoBuilder, "Non-Heap Memory Usage-Max", Long.toString(nonHeapMemoryUsage.getMax()));
    addInfo(infoBuilder, "Non-Heap Memory Usage-Used", Long.toString(nonHeapMemoryUsage.getUsed()));

    RuntimeMXBean RuntimemxBean = ManagementFactory.getRuntimeMXBean();
    StringBuilder vmArgumentBuilder = new StringBuilder();
    List<String> vmArguments = RuntimemxBean.getInputArguments();
    if (vmArguments != null) {
        for (String vmArgument : vmArguments) {
            if (InfoWriter.shouldMaskValue(vmArgument)) {
                vmArgument = Strings.maskKeyValue(vmArgument);
            }
            vmArgumentBuilder.append(vmArgument);
            if (vmArguments.indexOf(vmArgument) != (vmArguments.size() - 1)) {
                vmArgumentBuilder.append("\n");
            }
        }
    }

    infoBuilder.append("\nJVM Arguments:\n").append(vmArgumentBuilder.toString());

    return StringUtils.removeEnd(infoBuilder.toString(), "\n");
}

From source file:mondrian.util.UtilCompatibleJdk15.java

public Util.MemoryInfo getMemoryInfo() {
    return new Util.MemoryInfo() {
        protected final MemoryPoolMXBean TENURED_POOL = findTenuredGenPool();

        public Util.MemoryInfo.Usage get() {
            final MemoryUsage memoryUsage = TENURED_POOL.getUsage();
            return new Usage() {
                public long getUsed() {
                    return memoryUsage.getUsed();
                }/* ww  w  .jav a2  s .  co  m*/

                public long getCommitted() {
                    return memoryUsage.getCommitted();
                }

                public long getMax() {
                    return memoryUsage.getMax();
                }
            };
        }
    };
}

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

/**
 * Return some information regarding the memory status of the instance.
 *//*from   w ww.  j a v a  2 s. 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:org.romaframework.core.config.RomaApplicationContext.java

private void logMemoryUsage() {
    MemoryMXBean memBean = ManagementFactory.getMemoryMXBean();
    MemoryUsage heapMemory = memBean.getHeapMemoryUsage();
    MemoryUsage nonHeapMemory = memBean.getNonHeapMemoryUsage();

    NumberFormat nf = NumberFormat.getInstance();
    log.info("--------------- MEMORY USAGE ---------------");
    log.info("HEAP INIT MEMORY:       " + nf.format(heapMemory.getInit()) + " bytes");
    log.info("HEAP USED MEMORY:       " + nf.format(heapMemory.getUsed()) + " bytes");
    log.info("HEAP COMMITTED MEMORY:  " + nf.format(heapMemory.getCommitted()) + " bytes");
    log.info("HEAP MAX MEMORY:        " + nf.format(heapMemory.getMax()) + " bytes");
    log.info(" ");
    log.info("NON HEAP INIT MEMORY:       " + nf.format(nonHeapMemory.getInit()) + " bytes");
    log.info("NON HEAP USED MEMORY:       " + nf.format(nonHeapMemory.getUsed()) + " bytes");
    log.info("NON HEAP COMMITTED MEMORY:  " + nf.format(nonHeapMemory.getCommitted()) + " bytes");
    log.info("NON HEAP MAX MEMORY:        " + nf.format(nonHeapMemory.getMax()) + " bytes");
    log.info("--------------------------------------------");
}

From source file:org.helios.netty.jmx.MetricCollector.java

/**
 * Generates a {@link JSONObject} representing memory usage, plus the percentage usage of:<ul>
 * <li>Memory Allocated</li>
 * <li>Memory Maximum Capacity</li>
 * </ul>/*from w w  w .  j ava  2 s .  co m*/
 * @param usage The memory usage provided by the {@link MemoryMXBean}
 * @return A {@link JSONObject} 
 * @throws JSONException I have no idea why this would be thrown
 */
protected JSONObject processMemoryUsage(MemoryUsage usage) throws JSONException {
    JSONObject json = new JSONObject(usage);
    json.put("consumed(%)", calcPercent(usage.getUsed(), usage.getCommitted()));
    json.put("capacity(%)", calcPercent(usage.getUsed(), usage.getMax()));
    return json;
}

From source file:org.apache.hadoop.hbase.regionserver.metrics.RegionServerMetrics.java

@Override
public String toString() {
    StringBuilder sb = new StringBuilder();
    sb = Strings.appendKeyValue(sb, "requestsPerSecond",
            Integer.valueOf((int) this.requests.getPreviousIntervalValue()));
    sb = Strings.appendKeyValue(sb, "numberOfOnlineRegions", Integer.valueOf(this.regions.get()));
    sb = Strings.appendKeyValue(sb, "numberOfStores", Integer.valueOf(this.stores.get()));
    sb = Strings.appendKeyValue(sb, "numberOfStorefiles", Integer.valueOf(this.storefiles.get()));
    sb = Strings.appendKeyValue(sb, this.storefileIndexSizeMB.getName(),
            Integer.valueOf(this.storefileIndexSizeMB.get()));
    sb = Strings.appendKeyValue(sb, "rootIndexSizeKB", Integer.valueOf(this.rootIndexSizeKB.get()));
    sb = Strings.appendKeyValue(sb, "totalStaticIndexSizeKB",
            Integer.valueOf(this.totalStaticIndexSizeKB.get()));
    sb = Strings.appendKeyValue(sb, "totalStaticBloomSizeKB",
            Integer.valueOf(this.totalStaticBloomSizeKB.get()));
    sb = Strings.appendKeyValue(sb, this.memstoreSizeMB.getName(), Integer.valueOf(this.memstoreSizeMB.get()));
    sb = Strings.appendKeyValue(sb, "mbInMemoryWithoutWAL", Integer.valueOf(this.mbInMemoryWithoutWAL.get()));
    sb = Strings.appendKeyValue(sb, "numberOfPutsWithoutWAL", Long.valueOf(this.numPutsWithoutWAL.get()));
    sb = Strings.appendKeyValue(sb, "readRequestsCount", Long.valueOf(this.readRequestsCount.get()));
    sb = Strings.appendKeyValue(sb, "writeRequestsCount", Long.valueOf(this.writeRequestsCount.get()));
    sb = Strings.appendKeyValue(sb, "compactionQueueSize", Integer.valueOf(this.compactionQueueSize.get()));
    sb = Strings.appendKeyValue(sb, "flushQueueSize", Integer.valueOf(this.flushQueueSize.get()));
    // Duplicate from jvmmetrics because metrics are private there so
    // inaccessible.
    MemoryUsage memory = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage();
    sb = Strings.appendKeyValue(sb, "usedHeapMB", Long.valueOf(memory.getUsed() / MB));
    sb = Strings.appendKeyValue(sb, "maxHeapMB", Long.valueOf(memory.getMax() / MB));
    sb = Strings.appendKeyValue(sb, this.blockCacheSize.getName() + "MB",
            StringUtils.limitDecimalTo2((float) this.blockCacheSize.get() / MB));
    sb = Strings.appendKeyValue(sb, this.blockCacheFree.getName() + "MB",
            StringUtils.limitDecimalTo2((float) this.blockCacheFree.get() / MB));
    sb = Strings.appendKeyValue(sb, this.blockCacheCount.getName(), Long.valueOf(this.blockCacheCount.get()));
    sb = Strings.appendKeyValue(sb, this.blockCacheHitCount.getName(),
            Long.valueOf(this.blockCacheHitCount.get()));
    sb = Strings.appendKeyValue(sb, this.blockCacheMissCount.getName(),
            Long.valueOf(this.blockCacheMissCount.get()));
    sb = Strings.appendKeyValue(sb, this.blockCacheEvictedCount.getName(),
            Long.valueOf(this.blockCacheEvictedCount.get()));
    sb = Strings.appendKeyValue(sb, this.blockCacheHitRatio.getName(),
            Long.valueOf(this.blockCacheHitRatio.get()) + "%");
    sb = Strings.appendKeyValue(sb, this.blockCacheHitCachingRatio.getName(),
            Long.valueOf(this.blockCacheHitCachingRatio.get()) + "%");
    sb = Strings.appendKeyValue(sb, this.hdfsBlocksLocalityIndex.getName(),
            Long.valueOf(this.hdfsBlocksLocalityIndex.get()));
    sb = Strings.appendKeyValue(sb, "slowHLogAppendCount", Long.valueOf(this.slowHLogAppendCount.get()));
    sb = appendHistogram(sb, this.fsReadLatencyHistogram);
    sb = appendHistogram(sb, this.fsPreadLatencyHistogram);
    sb = appendHistogram(sb, this.fsWriteLatencyHistogram);

    return sb.toString();
}

From source file:fr.tpt.atlanalyser.examples.ExampleRunner.java

public void executePost2Pre(File postFile, int maxNumRuleIterations) throws IOException {
    // checkDirs();
    inputMM = getInputMMEPkg();//ww  w  .  j a v  a2  s  .c om
    outputMM = getOutputMMEPkg();
    makeAbstractClassesInstantiable(inputMM);
    makeAbstractClassesInstantiable(outputMM);
    Module transfo = loadHenshinTransformation();

    EcoreUtil.resolveAll(transfo);

    EPackage traceMM = resourceSet.getPackageRegistry().getEPackage("http://traces/1.0");

    stripFromAttributes(transfo);

    Resource postRes = resourceSet.getResource(URI.createFileURI(postFile.getCanonicalPath()), true);
    Module postModule = (Module) postRes.getContents().get(0);
    EList<Unit> units = postModule.getUnits();
    List<Formula> postconditions = Lists.transform(units, new Function<Unit, Formula>() {
        @Override
        public Formula apply(Unit arg0) {
            return ((Rule) arg0).getLhs().getFormula();
        }
    });

    Module preModule = HenshinFactory.eINSTANCE.createModule();
    preModule.setName("Preconditions");

    LOGGER.info("Starting Post2Pre for {}", transfo.getName());

    Post2Pre4ATL post2Pre = new Post2Pre4ATL(transfo, inputMM, outputMM, traceMM, jobs);

    ScheduledExecutorService memMonitorExecutor = Executors.newScheduledThreadPool(1);
    memMonitorExecutor.scheduleAtFixedRate(new Runnable() {

        private final MemoryMXBean memoryBean = ManagementFactory.getMemoryMXBean();
        private final Logger LOGGER = LogManager.getLogger("MemMon");

        @Override
        public void run() {
            // LOGGER.setAdditivity(false);

            // for (Enumeration iterator =
            // AGGWrapper.LOGGER.getAllAppenders(); iterator
            // .hasMoreElements();) {
            // Appender appender = (Appender) iterator.nextElement();
            // LOGGER.addAppender(appender);
            // }

            MemoryUsage heapUsage = memoryBean.getHeapMemoryUsage();
            final long used = heapUsage.getUsed();
            double usedGB = (double) used / (1 << 30);
            final long max = heapUsage.getMax();
            double maxGB = (double) max / (1 << 30);
            LOGGER.info(String.format("Memory use : %6.3fGB of %6.3fGB (%.2f%%)", usedGB, maxGB,
                    (float) used / max * 100));
        }
    }, 0, 10, TimeUnit.SECONDS);

    try {
        for (Formula formula : postconditions) {
            Formula pre = post2Pre.post2Pre(formula, maxNumRuleIterations);
            Rule preRule = HenshinFactory.eINSTANCE.createRule();
            Graph preLhs = HenshinFactory.eINSTANCE.createGraph();
            preLhs.setFormula(EcoreUtil.copy(pre));
            preRule.setLhs(preLhs);
            preModule.getUnits().add(preRule);
        }
    } finally {
        memMonitorExecutor.shutdown();
    }

    File outputDir = new File(baseDir, "Preconditions");
    if (!outputDir.isDirectory()) {
        outputDir.mkdir();
    }

    Resource outputRes = resourceSet
            .createResource(URI.createFileURI("Preconditions/" + postFile.getName() + "_pre.henshin"));

    outputRes.getContents().add(preModule);

    LOGGER.info("Writing Precondition in {}", outputRes.getURI().toString());
    outputRes.save(xmiSaveOptions);

    LOGGER.info("Done!");
}

From source file:org.apache.cassandra.tools.NodeCmd.java

/**
 * Write node information.//from  w w w  .  ja v  a 2  s.  co  m
 * 
 * @param outs the stream to write to
 */
public void printInfo(PrintStream outs) {
    boolean gossipInitialized = probe.isInitialized();
    outs.println(probe.getToken());
    outs.printf("%-17s: %s%n", "Gossip active", gossipInitialized);
    outs.printf("%-17s: %s%n", "Load", probe.getLoadString());
    if (gossipInitialized)
        outs.printf("%-17s: %s%n", "Generation No", probe.getCurrentGenerationNumber());
    else
        outs.printf("%-17s: %s%n", "Generation No", 0);

    // Uptime
    long secondsUp = probe.getUptime() / 1000;
    outs.printf("%-17s: %d%n", "Uptime (seconds)", secondsUp);

    // Memory usage
    MemoryUsage heapUsage = probe.getHeapMemoryUsage();
    double memUsed = (double) heapUsage.getUsed() / (1024 * 1024);
    double memMax = (double) heapUsage.getMax() / (1024 * 1024);
    outs.printf("%-17s: %.2f / %.2f%n", "Heap Memory (MB)", memUsed, memMax);
}