Example usage for java.lang Runtime freeMemory

List of usage examples for java.lang Runtime freeMemory

Introduction

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

Prototype

public native long freeMemory();

Source Link

Document

Returns the amount of free memory in the Java Virtual Machine.

Usage

From source file:org.onosproject.ospf.controller.impl.Controller.java

public Map<String, Long> getMemory() {
    Map<String, Long> m = new HashMap<>();
    Runtime runtime = Runtime.getRuntime();
    m.put("total", runtime.totalMemory());
    m.put("free", runtime.freeMemory());
    return m;//ww w .j a v a  2s .com
}

From source file:onlinefrontlines.admin.web.ServerInfoAction.java

/**
  * Execute the action/*from  w w w  .  j  a v  a  2 s . c om*/
  */
protected WebView execute() throws Exception {
    Runtime r = Runtime.getRuntime();

    // Get stats
    date = new Date().toString();
    committedMemory = r.totalMemory();
    maxMemory = r.maxMemory();
    usedMemory = committedMemory - r.freeMemory();
    cpuCount = Runtime.getRuntime().availableProcessors();
    os = System.getProperty("os.name") + " (" + System.getProperty("sun.os.patch.level") + ") "
            + System.getProperty("os.arch") + " " + System.getProperty("os.version");
    jvm = System.getProperty("java.runtime.name") + " " + System.getProperty("java.runtime.version") + " "
            + System.getProperty("java.vm.name");
    for (String s : DbConnectionPool.getInstance().getDataSources().keySet())
        dataSourceStatus.put(s, getDataSourceStatus(s));
    servletContainer = servletContext.getServerInfo();

    return getSuccessView();
}

From source file:eu.openanalytics.rsb.component.SystemHealthResource.java

@GET
@Path("/info")
@Produces({ Constants.RSB_XML_CONTENT_TYPE, Constants.RSB_JSON_CONTENT_TYPE })
public NodeInformation getInfo(@Context final ServletContext sc) {
    final NodeInformation info = Util.REST_OBJECT_FACTORY.createNodeInformation();

    info.setName(getConfiguration().getNodeName());
    info.setHealthy(nodeHealthy.get());//from ww w  .j a  va  2s.  c o  m
    info.setRsbVersion(getClass().getPackage().getImplementationVersion());
    info.setServletContainerInfo(sc.getServerInfo());

    final OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean();
    info.setOsLoadAverage(operatingSystemMXBean.getSystemLoadAverage());

    final Runtime runtime = Runtime.getRuntime();
    info.setJvmMaxMemory(runtime.maxMemory());
    info.setJvmFreeMemory(runtime.freeMemory());

    final RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
    final long uptimeMilliseconds = runtimeMXBean.getUptime();
    info.setUptime(uptimeMilliseconds);
    info.setUptimeText(DurationFormatUtils.formatDurationWords(uptimeMilliseconds, true, true));

    return info;
}

From source file:imageencode.ImageEncode.java

public void decode(final String filePath, final Element node) throws IOException {
    final File imageFile = new File(filePath);
    final OutputStream os = new FileOutputStream(imageFile);
    String encodedImage = node.getTextContent();
    // String decoded = decode(encodedImage);
    // os.write(decoded);
    final Runtime runtime = Runtime.getRuntime();
    System.out.println("Free memory : " + runtime.freeMemory());
    String[] sei = encodedImage.split("\r\n");
    // System.out.println(encodedImage);
    System.out.println("Free memory : " + runtime.freeMemory());
    for (final String element : sei) {
        final byte[] byteImage = Base64.decodeBase64(element);
        try {/*from   w  w  w  . ja v a2s  . co  m*/
            os.write(byteImage);
        } catch (final FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    os.close();
    System.out.println("Free memory : " + runtime.freeMemory());
    encodedImage = null;
    sei = null;
    System.gc();
    System.out.println("Free memory : " + runtime.freeMemory());
}

From source file:ImageEncode.java

public void decode(String filePath, Element node) throws IOException {
    final File imageFile = new File(filePath);
    final OutputStream os = new FileOutputStream(imageFile);
    String encodedImage = node.getTextContent();
    // String decoded = decode(encodedImage);
    // os.write(decoded);
    final Runtime runtime = Runtime.getRuntime();
    System.out.println("Free memory : " + runtime.freeMemory());
    String[] sei = encodedImage.split("\r\n");
    // System.out.println(encodedImage);
    System.out.println("Free memory : " + runtime.freeMemory());
    for (final String element : sei) {
        final byte[] byteImage = Base64.decodeBase64(element);
        try {/*from w w w.  j  a  v  a2  s  . c o m*/
            os.write(byteImage);
        } catch (final FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    os.close();
    System.out.println("Free memory : " + runtime.freeMemory());
    encodedImage = null;
    sei = null;
    System.gc();
    System.out.println("Free memory : " + runtime.freeMemory());
}

From source file:ca.simplegames.micro.controllers.StatsController.java

public void execute(MicroContext context, Map configuration) throws ControllerException {
    Map<String, Object> systemInfo = new HashMap<String, Object>();
    Map<String, Object> osMap = new HashMap<String, Object>();
    MBeanServerConnection mbeanServer = ManagementFactory.getPlatformMBeanServer();

    OperatingSystemMXBean sunOperatingSystemMXBean = null;
    try {//from w w  w .  j  a  v a 2 s. c o  m
        sunOperatingSystemMXBean = ManagementFactory.newPlatformMXBeanProxy(mbeanServer,
                ManagementFactory.OPERATING_SYSTEM_MXBEAN_NAME, OperatingSystemMXBean.class);
    } catch (IOException e) {
        throw new ControllerException(e.getMessage());
    }

    Runtime rt = Runtime.getRuntime();
    long totalMemory = rt.totalMemory() / MEGA_BYTE;
    long freeMemory = rt.freeMemory() / MEGA_BYTE;
    long usedMemory = totalMemory - freeMemory;

    final long p100 = (int) Math.round(((double) freeMemory / (double) totalMemory) * 100);

    Map<String, Long> memInfo = new HashMap<String, Long>();

    memInfo.put("total", totalMemory);
    memInfo.put("used", usedMemory);
    memInfo.put("free", freeMemory);
    memInfo.put("percent_free", p100);

    systemInfo.put("memory", memInfo);
    systemInfo.put("powered_by", POWERED_BY_MICRO);

    //cpu usage in milli secs
    long currentCpuUsage = sunOperatingSystemMXBean.getProcessCpuTime() / 1000000;
    osMap.put("cpu_usage", currentCpuUsage);
    osMap.put("available_processors", sunOperatingSystemMXBean.getAvailableProcessors());
    osMap.put("system_load_average", sunOperatingSystemMXBean.getSystemLoadAverage());
    osMap.put("committed_virtual_memory_size", sunOperatingSystemMXBean.getCommittedVirtualMemorySize());
    osMap.put("free_physical_memory_size", sunOperatingSystemMXBean.getFreePhysicalMemorySize());
    osMap.put("total_physical_memory_size", sunOperatingSystemMXBean.getTotalPhysicalMemorySize());
    osMap.put("free_swap_space_size", sunOperatingSystemMXBean.getFreeSwapSpaceSize());
    osMap.put("total_swap_space_size", sunOperatingSystemMXBean.getTotalSwapSpaceSize());

    systemInfo.put("os", osMap);

    List<GarbageCollectorMXBean> gc = ManagementFactory.getGarbageCollectorMXBeans();
    List<Map> gcInfo = new ArrayList<Map>();

    for (GarbageCollectorMXBean aGc : gc) {
        Map<String, Object> gcMap = new HashMap<String, Object>();
        gcMap.put("name", aGc.getName());
        gcMap.put("collection_count", aGc.getCollectionCount());
        gcMap.put("collection_time", aGc.getCollectionTime());

        gcInfo.add(gcMap);
    }

    systemInfo.put("gc", gcInfo);

    ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
    Map<String, Object> threadInfoMap = new HashMap<String, Object>(); // more to come ;)
    threadInfoMap.put("peak_thread_count", threadMXBean.getPeakThreadCount());
    threadInfoMap.put("thread_count", threadMXBean.getThreadCount());
    threadInfoMap.put("total_started_thread_count", threadMXBean.getTotalStartedThreadCount());

    long[] deadlockedThreads = threadMXBean.findMonitorDeadlockedThreads();
    threadInfoMap.put("dead_locked_thread_count", deadlockedThreads != null ? deadlockedThreads.length : 0);
    systemInfo.put("thread_info", threadInfoMap);

    JSONObject sysinfoJson = new JSONObject(Collections.singletonMap("system_info", systemInfo));

    String sysinfoString = null;
    try {
        sysinfoString = context.getRequest().getParameter("pretty") != null ? sysinfoJson.toString(2)
                : sysinfoJson.toString();
    } catch (JSONException e) {
        e.printStackTrace();
        throw new ControllerException(e.getMessage());
    }

    context.getRackResponse().withContentType(Mime.mimeType(JSON_TYPE)).withBody(sysinfoString)
            .withContentLength(sysinfoString.length()).with(Rack.MESSAGE_STATUS, HttpServletResponse.SC_OK);

    context.halt();
}

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/*from  w ww  . j  a v  a2 s . co  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.gargoylesoftware.htmlunit.javascript.configuration.JavaScriptConfigurationTest.java

private String getMemoryStats() {
    final Runtime rt = Runtime.getRuntime();
    final long free = rt.freeMemory() / 1024;
    final long total = rt.totalMemory() / 1024;
    final long max = rt.maxMemory() / 1024;
    final long used = total - free;
    final String format = "used: {0,number,0}K, free: {1,number,0}K, total: {2,number,0}K, max: {3,number,0}K";
    return MessageFormat.format(format, Long.valueOf(used), Long.valueOf(free), Long.valueOf(total),
            Long.valueOf(max));// w ww. ja  v  a2  s .c o  m
}

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: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  ww  w  .j  a  v  a 2 s  .  c  om*/
    return usage;
}