Example usage for java.lang Runtime totalMemory

List of usage examples for java.lang Runtime totalMemory

Introduction

In this page you can find the example usage for java.lang Runtime totalMemory.

Prototype

public native long totalMemory();

Source Link

Document

Returns the total amount of memory in the Java virtual machine.

Usage

From source file:com.liferay.portal.events.GarbageCollectorAction.java

public void run(HttpSession ses) throws ActionException {

    try {//from   w  w  w  . j av a 2s .c  o m
        Runtime runtime = Runtime.getRuntime();

        NumberFormat nf = NumberFormat.getInstance();

        _log.debug("Before GC: " + nf.format(runtime.freeMemory()) + " free, "
                + nf.format(runtime.totalMemory()) + " total, and " + nf.format(runtime.maxMemory()) + " max");

        _log.debug("Running garbage collector");

        System.gc();

        _log.debug("After GC: " + nf.format(runtime.freeMemory()) + " free, " + nf.format(runtime.totalMemory())
                + " total, and " + nf.format(runtime.maxMemory()) + " max");
    } catch (Exception e) {
        throw new ActionException(e);
    }
}

From source file:models.monitor.MonitorProvider.java

public PerformUsage getJVMMemoryUsage() {
    int mb = 1024 * 1024;
    Runtime rt = Runtime.getRuntime();
    PerformUsage usage = new PerformUsage();
    usage.totalMemory = (double) rt.totalMemory() / mb;
    usage.freeMemory = (double) rt.freeMemory() / mb;
    usage.usedMemory = (double) rt.totalMemory() / mb - rt.freeMemory() / mb;
    usage.maxMemory = (double) rt.maxMemory() / mb;
    usage.memoryUsagePercent = usage.usedMemory / usage.totalMemory * 100.0;

    //            new BigDecimal().setScale(2) .divide(new BigDecimal(usage.totalMemory).setScale(2), RoundingMode.DOWN)
    //                                                  .setScale(2)
    //                                                  .multiply(new BigDecimal(100)).intValue();

    // update current
    currentJvmPerformUsage = usage;/*from   w  ww .j a  v a 2  s  .  co  m*/
    return usage;
}

From source file:edu.umn.cs.spatialHadoop.visualization.MultilevelPlot.java

public static Job plot(Path[] inPaths, Path outPath, Class<? extends Plotter> plotterClass,
        OperationsParams params) throws IOException, InterruptedException, ClassNotFoundException {
    if (params.getBoolean("showmem", false)) {
        // Run a thread that keeps track of used memory
        Thread memThread = new Thread(new Thread() {
            @Override/*w ww.  j a v a  2  s.c  o m*/
            public void run() {
                Runtime runtime = Runtime.getRuntime();
                while (true) {
                    try {
                        Thread.sleep(60000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    runtime.gc();
                    LOG.info("Memory usage: "
                            + ((runtime.totalMemory() - runtime.freeMemory()) / (1024 * 1024 * 1024)) + "GB.");
                }
            }
        });
        memThread.setDaemon(true);
        memThread.start();
    }

    // Decide how to run it based on range of levels to generate
    String[] strLevels = params.get("levels", "7").split("\\.\\.");
    int minLevel, maxLevel;
    if (strLevels.length == 1) {
        minLevel = 0;
        maxLevel = Integer.parseInt(strLevels[0]) - 1;
    } else {
        minLevel = Integer.parseInt(strLevels[0]);
        maxLevel = Integer.parseInt(strLevels[1]);
    }
    // Create an output directory that will hold the output of the two jobs
    FileSystem outFS = outPath.getFileSystem(params);
    outFS.mkdirs(outPath);

    Job runningJob = null;
    if (OperationsParams.isLocal(params, inPaths)) {
        // Plot local
        plotLocal(inPaths, outPath, plotterClass, params);
    } else {
        int maxLevelWithFlatPartitioning = params.getInt(FlatPartitioningLevelThreshold, 4);
        if (minLevel <= maxLevelWithFlatPartitioning) {
            OperationsParams flatPartitioning = new OperationsParams(params);
            flatPartitioning.set("levels", minLevel + ".." + Math.min(maxLevelWithFlatPartitioning, maxLevel));
            flatPartitioning.set("partition", "flat");
            LOG.info("Using flat partitioning in levels " + flatPartitioning.get("levels"));
            runningJob = plotMapReduce(inPaths, new Path(outPath, "flat"), plotterClass, flatPartitioning);
        }
        if (maxLevel > maxLevelWithFlatPartitioning) {
            OperationsParams pyramidPartitioning = new OperationsParams(params);
            pyramidPartitioning.set("levels",
                    Math.max(minLevel, maxLevelWithFlatPartitioning + 1) + ".." + maxLevel);
            pyramidPartitioning.set("partition", "pyramid");
            LOG.info("Using pyramid partitioning in levels " + pyramidPartitioning.get("levels"));
            runningJob = plotMapReduce(inPaths, new Path(outPath, "pyramid"), plotterClass,
                    pyramidPartitioning);
        }
        // Write a new HTML file that displays both parts of the pyramid
        // Add an HTML file that visualizes the result using Google Maps
        LineReader templateFileReader = new LineReader(
                MultilevelPlot.class.getResourceAsStream("/zoom_view.html"));
        PrintStream htmlOut = new PrintStream(outFS.create(new Path(outPath, "index.html")));
        Text line = new Text();
        while (templateFileReader.readLine(line) > 0) {
            String lineStr = line.toString();
            lineStr = lineStr.replace("#{TILE_WIDTH}", Integer.toString(params.getInt("tilewidth", 256)));
            lineStr = lineStr.replace("#{TILE_HEIGHT}", Integer.toString(params.getInt("tileheight", 256)));
            lineStr = lineStr.replace("#{MAX_ZOOM}", Integer.toString(maxLevel));
            lineStr = lineStr.replace("#{MIN_ZOOM}", Integer.toString(minLevel));
            lineStr = lineStr.replace("#{TILE_URL}", "(zoom <= " + maxLevelWithFlatPartitioning
                    + "? 'flat' : 'pyramid')+('/tile-' + zoom + '-' + coord.x + '-' + coord.y + '.png')");

            htmlOut.println(lineStr);
        }
        templateFileReader.close();
        htmlOut.close();
    }

    return runningJob;
}

From source file:com.amazonaws.metrics.internal.cloudwatch.MachineMetricFactory.java

private void addMemoryMetrics(List<MetricDatum> targetList, Set<MachineMetric> customSet) {
    Runtime rt = Runtime.getRuntime();
    long totalMem = rt.totalMemory();
    long freeMem = rt.freeMemory();
    long usedMem = totalMem - freeMem;
    long spareMem = rt.maxMemory() - usedMem;
    List<Long> values = Arrays.asList(totalMem, freeMem, usedMem, spareMem);
    MetricValues metricValues = memoryMetricValues(customSet, values);
    addMetrics(targetList, metricValues, StandardUnit.Bytes);
}

From source file:com.github.lpezet.antiope.metrics.aws.MachineMetricFactory.java

private void addMemoryMetrics(List<MetricDatum> pTargetList, Set<MachineMetric> pCustomSet) {
    Runtime rt = Runtime.getRuntime();
    long oTotalMem = rt.totalMemory();
    long oFreeMem = rt.freeMemory();
    long oUsedMem = oTotalMem - oFreeMem;
    long oSpareMem = rt.maxMemory() - oUsedMem;
    List<Long> oValues = Arrays.asList(oTotalMem, oFreeMem, oUsedMem, oSpareMem);
    MetricValues oMetricValues = memoryMetricValues(pCustomSet, oValues);
    addMetrics(pTargetList, oMetricValues, StandardUnit.Bytes);
}

From source file:it.damore.tomee.envmonitor.services.EnvMonitorService.java

@GET
@Path("monitor")
@Produces({ MediaType.APPLICATION_JSON })
public EnvironmentConfig getEnvConfig() throws IllegalAccessException, InvocationTargetException {
    logger.info("received a request...");

    int mb = 1024 * 1024;
    //Getting the runtime reference from system
    Runtime runtime = Runtime.getRuntime();

    EnvironmentConfig b = new EnvironmentConfig();
    b.setMaxMemory(runtime.maxMemory() / mb);
    b.setFreeMemory(runtime.freeMemory() / mb);
    b.setTotalMemory(runtime.totalMemory() / mb);
    b.setSystemProperties(System.getProperties());

    RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
    LocalRuntimeMXBean myRuntimeMXBean = new LocalRuntimeMXBean();
    BeanUtils.copyProperties(myRuntimeMXBean, runtimeMXBean);
    b.setRuntimeMXBean(myRuntimeMXBean);

    MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean();
    LocalMemoryMXBean myMemoryMXBean = new LocalMemoryMXBean();
    myMemoryMXBean.setHeapMemoryUsage(memoryMXBean.getHeapMemoryUsage());
    myMemoryMXBean.setNonHeapMemoryUsage(memoryMXBean.getNonHeapMemoryUsage());
    myMemoryMXBean.setObjectPendingFinalizationCount(memoryMXBean.getObjectPendingFinalizationCount());
    b.setMemoryMXBean(myMemoryMXBean);//from w w  w. java  2  s  .  co  m

    OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean();
    LocalOperatingSystemMXBean myOperatingSystemMXBean = new LocalOperatingSystemMXBean();
    BeanUtils.copyProperties(myOperatingSystemMXBean, operatingSystemMXBean);
    b.setOperatingSystemMXBean(myOperatingSystemMXBean);

    return b;
}

From source file:org.alfresco.repo.content.transform.TikaPoweredContentTransformer.java

private String calculateMemoryAndTimeUsage(ContentReader reader, long startTime) {
    long endTime = System.currentTimeMillis();
    Runtime runtime = Runtime.getRuntime();
    long totalMemory = runtime.totalMemory();
    return String.format(USAGE_PATTERN, this.getClass().getName(), reader,
            (totalMemory - runtime.freeMemory()) / MEGABYTES, totalMemory / MEGABYTES,
            runtime.maxMemory() / MEGABYTES, (endTime - startTime));
}

From source file:ffx.HeadlessMain.java

/**
 * Complete initializations.//from   w w w. ja  v a2  s.  c  om
 *
 * @param commandLineFile a {@link java.io.File} object.
 * @param argList a {@link java.util.List} object.
 * @param logHandler a {@link ffx.ui.LogHandler} object.
 */
public HeadlessMain(File commandLineFile, List<String> argList, LogHandler logHandler) {
    // Start a timer.
    stopWatch.start();

    // Construct the MainPanel, set it's LogHandler, and initialize then it.
    mainPanel = new MainPanel();
    logHandler.setMainPanel(mainPanel);
    mainPanel.initialize();

    // Open the supplied script file.
    if (commandLineFile != null) {
        if (!commandLineFile.exists()) {
            /**
             * See if the commandLineFile is an embedded script.
             */
            String name = commandLineFile.getName();
            name = name.replace('.', '/');
            String pathName = "ffx/scripts/" + name;
            ClassLoader loader = getClass().getClassLoader();
            URL embeddedScript = loader.getResource(pathName + ".ffx");
            if (embeddedScript == null) {
                embeddedScript = loader.getResource(pathName + ".groovy");
            }
            if (embeddedScript != null) {
                try {
                    commandLineFile = new File(FFXClassLoader.copyInputStreamToTmpFile(
                            embeddedScript.openStream(), commandLineFile.getName(), ".ffx"));
                } catch (Exception e) {
                    logger.warning("Exception extracting embedded script " + embeddedScript.toString() + "\n"
                            + e.toString());
                }
            }
        }
        if (commandLineFile.exists()) {
            mainPanel.getModelingShell().setArgList(argList);
            mainPanel.open(commandLineFile, null);
        } else {
            logger.warning(format("%s was not found.", commandLineFile.toString()));
        }
    }

    /**
     * Print start-up information.
     */
    if (logger.isLoggable(Level.FINE)) {
        StringBuilder sb = new StringBuilder();
        sb.append(format("\n Start-up Time (msec): %s.", stopWatch.getTime()));
        Runtime runtime = Runtime.getRuntime();
        runtime.runFinalization();
        runtime.gc();
        long occupiedMemory = runtime.totalMemory() - runtime.freeMemory();
        long KB = 1024;
        sb.append(format("\n In-Use Memory   (Kb): %d", occupiedMemory / KB));
        sb.append(format("\n Free Memory     (Kb): %d", runtime.freeMemory() / KB));
        sb.append(format("\n Total Memory    (Kb): %d", runtime.totalMemory() / KB));
        logger.fine(sb.toString());
    }
}

From source file:org.apache.shindig.social.opensocial.util.JsonConverterPerformancePerf.java

public void testToJsonLibOnInheritedClassInput() throws Exception {
    SpecialPerson[] spa = new SpecialPerson[TEST_SIZE];
    SpecialPerson[] sparesult = new SpecialPerson[TEST_SIZE];
    Runtime r = Runtime.getRuntime();
    r.gc();//from   ww w . ja  va 2s.  c o m
    long personStart = r.totalMemory() - r.freeMemory();
    for (int i = 0; i < TEST_SIZE; i++) {
        spa[i] = new SpecialPerson(String.valueOf(i), "robot", "nonsense");
    }
    long personEnd = r.totalMemory() - r.freeMemory();

    String[] serializeOutput = new String[TEST_SIZE];
    r.gc();
    for (int i = 0; i < TEST_SIZE; i++) {

        serializeOutput[i] = beanJsonLibConverter.convertToString(spa[i]);
    }

    r.gc();
    long memstart = r.totalMemory() - r.freeMemory();
    long startInput = System.currentTimeMillis();
    for (int i = 0; i < TEST_SIZE; i++) {
        sparesult[i] = beanJsonLibConverter.convertToObject(serializeOutput[i], SpecialPerson.class);
    }
    long endInput = System.currentTimeMillis();
    long memend = r.totalMemory() - r.freeMemory();

    log.info("SF JSON Lib Input " + average(startInput, endInput, TEST_SIZE) + " ms/conversion, "
            + (average(memstart, memend, TEST_SIZE) - average(personStart, personEnd, TEST_SIZE))
            + " heap bytes/conversion, person object consumed on average "
            + average(personStart, personEnd, TEST_SIZE));
}

From source file:org.apache.shindig.social.opensocial.util.JsonConverterPerformancePerf.java

public void XtestToJsonOnInheritedClassInput() throws Exception {
    SpecialPerson[] spa = new SpecialPerson[TEST_SIZE];
    SpecialPerson[] sparesult = new SpecialPerson[TEST_SIZE];
    Runtime r = Runtime.getRuntime();
    r.gc();//ww w  .j  a va2  s  .  c  o m
    long personStart = r.totalMemory() - r.freeMemory();
    for (int i = 0; i < TEST_SIZE; i++) {
        spa[i] = new SpecialPerson(String.valueOf(i), "robot", "nonsense");
    }
    long personEnd = r.totalMemory() - r.freeMemory();

    String[] serializeOutput = new String[TEST_SIZE];
    r.gc();
    for (int i = 0; i < TEST_SIZE; i++) {

        serializeOutput[i] = beanJsonConverter.convertToString(spa[i]);
    }

    r.gc();
    long memstart = r.totalMemory() - r.freeMemory();
    long startInput = System.currentTimeMillis();

    for (int i = 0; i < TEST_SIZE; i++) {
        sparesult[i] = beanJsonConverter.convertToObject(serializeOutput[i], SpecialPerson.class);
    }
    long endInput = System.currentTimeMillis();
    long memend = r.totalMemory() - r.freeMemory();

    log.info("SF JSON Lib Input " + average(startInput, endInput, TEST_SIZE) + " ms/conversion, "
            + (average(memstart, memend, TEST_SIZE) - average(personStart, personEnd, TEST_SIZE))
            + " heap bytes/conversion, person object consumed on average "
            + average(personStart, personEnd, TEST_SIZE));
}