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:edu.ku.brc.ui.FeedBackSender.java

/**
 * Creates an array of POST method parameters to send with the version checking / usage tracking connection.
 * //from  ww  w  .  ja  va 2  s  .c o m
 * @param item the item to fill
 * @return an array of POST parameters
 */
protected NameValuePair[] createPostParameters(final FeedBackSenderItem item) {
    Vector<NameValuePair> postParams = new Vector<NameValuePair>();
    try {
        postParams.add(new NameValuePair("bug", item.getBug())); //$NON-NLS-1$
        postParams.add(new NameValuePair("class_name", item.getClassName())); //$NON-NLS-1$
        postParams.add(new NameValuePair("comments", item.getComments())); //$NON-NLS-1$
        postParams.add(new NameValuePair("stack_trace", item.getStackTrace())); //$NON-NLS-1$
        postParams.add(new NameValuePair("task_name", item.getTaskName())); //$NON-NLS-1$
        postParams.add(new NameValuePair("title", item.getTitle())); //$NON-NLS-1$

        // get the install ID
        String installID = UsageTracker.getInstallId();
        postParams.add(new NameValuePair("id", installID)); //$NON-NLS-1$

        Runtime runtime = Runtime.getRuntime();
        Long usedMemory = runtime.maxMemory() - (runtime.totalMemory() + runtime.freeMemory());
        Long maxMemory = runtime.maxMemory();

        // get the OS name and version
        postParams.add(new NameValuePair("os_name", System.getProperty("os.name"))); //$NON-NLS-1$ //$NON-NLS-2$
        postParams.add(new NameValuePair("os_version", System.getProperty("os.version"))); //$NON-NLS-1$ //$NON-NLS-2$
        postParams.add(new NameValuePair("java_version", System.getProperty("java.version"))); //$NON-NLS-1$ //$NON-NLS-2$
        postParams.add(new NameValuePair("java_vendor", System.getProperty("java.vendor"))); //$NON-NLS-1$ //$NON-NLS-2$
        postParams.add(new NameValuePair("max_memory", maxMemory.toString())); //$NON-NLS-1$
        postParams.add(new NameValuePair("used_memory", usedMemory.toString())); //$NON-NLS-1$

        Properties props = item.getProps();
        if (props != null) {
            for (Object key : props.keySet()) {
                postParams.add(new NameValuePair(key.toString(), props.getProperty(key.toString()))); //$NON-NLS-1$
            }
        }

        //if (!UIRegistry.isRelease()) // For Testing Only
        {
            postParams.add(new NameValuePair("user_name", System.getProperty("user.name"))); //$NON-NLS-1$
            try {
                postParams.add(new NameValuePair("ip", InetAddress.getLocalHost().getHostAddress())); //$NON-NLS-1$
            } catch (UnknownHostException e) {
            }
        }

        String resAppVersion = UIRegistry.getAppVersion();
        if (StringUtils.isEmpty(resAppVersion)) {
            resAppVersion = "Unknown";
        }
        postParams.add(new NameValuePair("app_version", resAppVersion)); //$NON-NLS-1$

        Vector<NameValuePair> extraStats = collectionSecondaryInfo(item);
        if (extraStats != null) {
            postParams.addAll(extraStats);
        }

        // create an array from the params
        NameValuePair[] paramArray = new NameValuePair[postParams.size()];
        for (int i = 0; i < paramArray.length; ++i) {
            paramArray[i] = postParams.get(i);
        }

        return paramArray;

    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return null;
}

From source file:org.wso2.carbon.mediation.statistics.monitor.EsbStatisticsConsumer.java

private void updateMemoryView(MemoryStatView view) {
    Runtime runtime = Runtime.getRuntime();

    view.setTotalMemory(runtime.totalMemory() / MEGA);
    view.setFreeMemory(runtime.freeMemory() / MEGA);
    view.setUsedMemory((runtime.totalMemory() - runtime.freeMemory()) / MEGA);
    view.setMaxMemory(runtime.maxMemory() / MEGA);
}

From source file:com.viettel.logistic.wms.business.KpiLogBusiness.java

private void checkMemory(String functionName, String transactionCode) {

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

    System.out.println("##### Heap utilization statistics [MB] #####");
    System.out.println("##### Transaction code = " + transactionCode + " #####");

    //Print used memory
    System.out.println(functionName + " Used Memory:" + (runtime.totalMemory() - runtime.freeMemory()) / mb);

    //Print free memory
    System.out.println(functionName + " Free Memory:" + runtime.freeMemory() / mb);

    //Print total available memory
    System.out.println(functionName + " Total Memory:" + runtime.totalMemory() / mb);

    //Print Maximum available memory
    System.out.println(functionName + " Max Memory:" + runtime.maxMemory() / mb);

}

From source file:ffx.ui.UIDataConverter.java

/**
 * Rather verbose output for timed File Operations makes it easy to grep log
 * files for specific information.//from ww w .jav  a 2s.  c om
 */
private void startTimer() {
    Runtime runtime = Runtime.getRuntime();
    if (gc) {
        runtime.runFinalization();
        runtime.gc();
    }
    occupiedMemory = runtime.totalMemory() - runtime.freeMemory();
    time -= System.nanoTime();
}

From source file:xc.mst.utils.TimingStats.java

private void outputMemory(boolean runGC) {
    if (runGC) {/*from w  w  w  .j ava2s .  c om*/
        System.gc();
    }
    Runtime r = Runtime.getRuntime();
    long maxMem = r.maxMemory() / 1048576;
    long totalMem = r.totalMemory() / 1048576;

    long freeBytes = r.freeMemory();
    long freeMem = freeBytes / 1048576;

    long usedMem = totalMem - freeMem;
    long memIncrease = usedMem - memUsedAtLastReset;
    memUsedAtLastReset = usedMem;

    LOG.debug("");
    LOG.debug("Free  memory: " + StringUtils.leftPad(freeMem + "", 7) + " MB.");
    LOG.debug("Used  memory: " + StringUtils.leftPad(usedMem + "", 7) + " MB.");
    LOG.debug("Increased by: " + StringUtils.leftPad(memIncrease + "", 7) + " MB.");
    LOG.debug("Total memory: " + StringUtils.leftPad(totalMem + "", 7) + " MB.");
    LOG.debug("Max'm memory: " + StringUtils.leftPad(maxMem + "", 7) + " MB.");

    //double percentageUsed = ((double) usedMem) / maxMem;
    //System.out.println("percentageUsed = " + percentageUsed);
    //MemoryWarningSystem.setPercentageUsageThreshold(0.8);  // 80%
}

From source file:ffx.ui.UIDataConverter.java

private void stopTimer(FFXSystem ffxSystem) {
    time += System.nanoTime();/*ww  w. j ava 2s . c  o m*/
    logger.log(Level.INFO, " Opened {0} with {1} atoms.\n File Op Time  (msec): {2}",
            new Object[] { ffxSystem.toString(), ffxSystem.getAtomList().size(), time * 1.0e-9 });
    Runtime runtime = Runtime.getRuntime();
    if (gc) {
        runtime.runFinalization();
        runtime.gc();
        long moleculeMemory = (runtime.totalMemory() - runtime.freeMemory()) - occupiedMemory;
        logger.log(Level.INFO, " System Memory  (Kb): {0}", moleculeMemory / KB);
    }
    occupiedMemory = runtime.totalMemory() - runtime.freeMemory();
    if (gc) {
        logger.log(Level.INFO, " Memory In Use  (Kb): {0}", occupiedMemory / KB);
    }
}

From source file:org.apache.maven.cli.event.ExecutionEventLogger.java

private void logStats(MavenSession session) {
    logger.info(chars('-', LINE_LENGTH));

    long finish = System.currentTimeMillis();

    long time = finish - session.getRequest().getStartTime().getTime();

    String wallClock = session.getRequest().getDegreeOfConcurrency() > 1 ? " (Wall Clock)" : "";

    logger.info("Total time: " + formatDuration(time) + wallClock);

    logger.info("Finished at: " + formatTimestamp(finish));

    System.gc();//w  w w.  j ava2  s . com

    Runtime r = Runtime.getRuntime();

    long mb = 1024 * 1024;

    logger.info("Final Memory: " + (r.totalMemory() - r.freeMemory()) / mb + "M/" + r.totalMemory() / mb + "M");
}

From source file:org.uva.itast.TestOMRProcessor.java

@Test
public void testProcessMultiPagePDFmultiDefinitions() {
    try {/*from   w ww  .j  a  v a  2  s.co  m*/
        //        if (false) 
        //             return;

        URL url = getClass().getClassLoader().getResource("56605.pdf");
        File testPath = new File(url.toURI());

        // use a single, common, template definition
        prepareConfig(testPath);
        File dir = testPath.getParentFile();
        Vector<PageImage> errores;

        if (logger.isInfoEnabled()) {
            logger.info("Test with definitions in a zip."); //$NON-NLS-1$
        }

        processor.getTemplates().clear();
        File zipDefinitions = new File(dir, "form_test.zip");
        processor.loadTemplateCollection(zipDefinitions.getAbsolutePath());

        detectErrors(testPath);
        // deteccin de errores
        // use a collection of templates from a directory
        if (logger.isInfoEnabled()) {
            logger.info("Test with definitions in a directory."); //$NON-NLS-1$
        }
        processor.getTemplates().clear();
        processor.loadTemplateCollection(dir.getAbsolutePath());

        detectErrors(testPath);

    } catch (Exception e) {
        fail("Can't configure test case." + e);
    } catch (OutOfMemoryError err) {
        Runtime runtime = Runtime.getRuntime();
        long totalMemory = runtime.totalMemory();
        long freeMemory = runtime.freeMemory();
        long maxMemory = runtime.maxMemory();
        String errorMsg = "testProcessMultiPagePDFmultiDefinitions(): Out of Memory.\n" + "Total:" + totalMemory
                + "\n" + "Max:" + maxMemory + "\n" + "Free:" + freeMemory;
        logger.fatal(errorMsg, err); //$NON-NLS-1$
        fail(errorMsg);
    }
}

From source file:org.ambraproject.action.debug.DebugInfoAction.java

@Override
public String execute() throws Exception {
    if (!checkAccess()) {
        return ERROR;
    }//from   ww  w  .  j a  v a 2  s  .c o  m
    timestamp = new Date(System.currentTimeMillis());
    Runtime rt = Runtime.getRuntime();
    jvmFreeMemory = (double) rt.freeMemory() / (1024.0 * 1024.0);
    jvmTotalMemory = (double) rt.totalMemory() / (1024.0 * 1024.0);
    jvmMaxMemory = (double) rt.maxMemory() / (1024.0 * 1024.0);
    HttpServletRequest req = ServletActionContext.getRequest();
    tomcatVersion = ServletActionContext.getServletContext().getServerInfo();
    sessionCount = SessionCounter.getSessionCount();
    host = req.getLocalName();
    hostIp = req.getLocalAddr();
    buildInfo = generateBuildInfo();

    // The easiest way I found to get the URL and username for the DB.
    // It's not that easy and involves opening a connection...
    Context initialContext = new InitialContext();
    Context context = (Context) initialContext.lookup("java:comp/env");
    DataSource ds = (DataSource) context.lookup("jdbc/AmbraDS");
    Connection conn = null;
    try {
        conn = ds.getConnection();
        DatabaseMetaData metadata = conn.getMetaData();
        dbUrl = metadata.getURL();
        dbUser = metadata.getUserName();
    } finally {
        conn.close();
    }

    Configuration config = ConfigurationStore.getInstance().getConfiguration();
    FileStoreService filestoreService = (FileStoreService) context.lookup("ambra/FileStore");
    filestore = filestoreService.toString();
    solrUrl = (String) config.getProperty("ambra.services.search.server.url");
    configuration = dumpConfig(config);
    cmdLine = IOUtils.toString(new FileInputStream("/proc/self/cmdline"));

    return SUCCESS;
}

From source file:com.ikon.servlet.admin.StatsGraphServlet.java

/**
 * Generate memory statistics// w ww.  ja v a  2 s  . co  m
 * http://blog.codebeach.com/2008/02/determine-available-memory-in-java.html
 */
public JFreeChart jvmMemStats() throws IOException, ServletException {
    Runtime runtime = Runtime.getRuntime();
    long max = runtime.maxMemory(); // maximum amount of memory that the JVM will attempt to use
    long available = runtime.totalMemory(); // total amount of memory in the JVM
    long free = runtime.freeMemory(); // amount of free memory in the JVM
    long used = max - available;
    long total = free + used;
    String title = "JVM memory: " + FormatUtil.formatSize(total);

    log.debug("JVM maximun memory: {}", FormatUtil.formatSize(max));
    log.debug("JVM available memory: {}", FormatUtil.formatSize(available));
    log.debug("JVM free memory: {}", FormatUtil.formatSize(free));
    log.debug("JVM used memory: {}", FormatUtil.formatSize(used));
    log.debug("JVM total memory: {}", FormatUtil.formatSize(total));

    DefaultPieDataset dataset = new DefaultPieDataset();
    dataset.setValue("Available (" + FormatUtil.formatSize(free) + ")", free * 100 / total);
    dataset.setValue("Used (" + FormatUtil.formatSize(used) + ")", used * 100 / total);

    return ChartFactory.createPieChart(title, dataset, true, false, false);
}