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:qa.qcri.nadeef.test.core.SQLTableTest.java

public void testSize() throws InterruptedException {
    Stopwatch stopwatch = Stopwatch.createStarted();
    SQLTable table = new SQLTable("TB_test60m", connectionFactory);
    table.get(0);//from   w w  w. j av  a  2 s . co  m

    long elapsedTime = stopwatch.elapsed(TimeUnit.MILLISECONDS);
    int mb = 1024 * 1024;

    //Getting the runtime reference from system
    Runtime runtime = Runtime.getRuntime();

    System.out.println("##### Heap utilization statistics [MB] #####");

    long usedMemory = (runtime.totalMemory() - runtime.freeMemory()) / mb;
    System.out.println("Used Memory:" + usedMemory);
    System.out.println("Free Memory:" + runtime.freeMemory() / mb);
    System.out.println("Total Memory:" + runtime.totalMemory() / mb);
    System.out.println("Max Memory:" + runtime.maxMemory() / mb);
    System.out.println("Load time: " + elapsedTime + " ms.");

    // memory usage should be less than 700 mb.
    Assert.assertTrue(usedMemory < 700);

    // load time should be less than 18000 ms
    Assert.assertTrue(elapsedTime < 18000);
}

From source file:ai.susi.server.api.susi.StatusService.java

@Override
public JSONObject serviceImpl(Query post, HttpServletResponse response, Authorization rights,
        JsonObjectWithDefault permissions) throws APIException {

    post.setResponse(response, "application/javascript");

    // generate json
    Runtime runtime = Runtime.getRuntime();
    JSONObject json = new JSONObject(true);
    JSONObject system = new JSONObject(true);
    system.put("assigned_memory", runtime.maxMemory());
    system.put("used_memory", runtime.totalMemory() - runtime.freeMemory());
    system.put("available_memory", runtime.maxMemory() - runtime.totalMemory() + runtime.freeMemory());
    system.put("cores", runtime.availableProcessors());
    system.put("threads", Thread.activeCount());
    system.put("runtime", System.currentTimeMillis() - Caretaker.startupTime);
    system.put("load_system_average", OS.getSystemLoadAverage());
    system.put("load_system_cpu", OS.getSystemCpuLoad());
    system.put("load_process_cpu", OS.getProcessCpuLoad());
    system.put("server_threads", SusiServer.getServerThreads());
    system.put("server_uri", SusiServer.getServerURI());

    JSONObject index = new JSONObject(true);
    JSONObject messages = new JSONObject(true);
    JSONObject queue = new JSONObject(true);
    messages.put("queue", queue);
    JSONObject users = new JSONObject(true);
    JSONObject queries = new JSONObject(true);
    JSONObject accounts = new JSONObject(true);
    JSONObject user = new JSONObject(true);
    index.put("messages", messages);
    index.put("users", users);
    index.put("queries", queries);
    index.put("accounts", accounts);
    index.put("user", user);

    JSONObject client_info = new JSONObject(true);
    client_info.put("RemoteHost", post.getClientHost());
    client_info.put("IsLocalhost", post.isLocalhostAccess() ? "true" : "false");

    JSONObject request_header = new JSONObject(true);
    Enumeration<String> he = post.getRequest().getHeaderNames();
    while (he.hasMoreElements()) {
        String h = he.nextElement();
        request_header.put(h, post.getRequest().getHeader(h));
    }//from  w w w .j a  v a 2s.  c  o  m
    client_info.put("request_header", request_header);

    json.put("system", system);
    json.put("index", index);
    json.put("client_info", client_info);

    return json;
}

From source file:com.openddal.test.BaseTestCase.java

/**
 * Get the number of bytes heap memory in use.
 *
 * @return the used bytes//from w  ww . j ava 2  s.  co m
 */
public static long getMemoryUsedBytes() {
    Runtime rt = Runtime.getRuntime();
    long memory = Long.MAX_VALUE;
    for (int i = 0; i < 8; i++) {
        rt.gc();
        long memNow = rt.totalMemory() - rt.freeMemory();
        if (memNow >= memory) {
            break;
        }
        memory = memNow;
    }
    return memory;
}

From source file:tachyon.master.InodeFolderTest.java

@Test
public void getChildTest() {
    // large number of small files
    InodeFolder inodeFolder = new InodeFolder("testFolder1", 1, 0, System.currentTimeMillis());
    int nFiles = (int) 1E5;
    Inode[] inodes = new Inode[nFiles];
    for (int i = 0; i < nFiles; i++) {
        inodes[i] = new InodeFile(String.format("testFile%d", i + 1), i + 2, 1, 1, System.currentTimeMillis());
        inodeFolder.addChild(inodes[i]);
    }/*  w w  w  .  j  av  a2s.  co m*/

    Runtime runtime = Runtime.getRuntime();
    System.out.println(String.format("Used Memory = %dB when number of files = %d",
            runtime.totalMemory() - runtime.freeMemory(), nFiles));

    long start = System.currentTimeMillis();
    for (int i = 0; i < nFiles; i++) {
        Assert.assertEquals(inodes[i], inodeFolder.getChild(i + 2));
    }
    System.out.println(String.format("getChild(int fid) called sequentially %d times, cost %d ms", nFiles,
            System.currentTimeMillis() - start));

    start = System.currentTimeMillis();
    for (int i = 0; i < nFiles; i++) {
        Assert.assertEquals(inodes[i], inodeFolder.getChild(String.format("testFile%d", i + 1)));
    }
    System.out.println(String.format("getChild(String name) called sequentially %d times, cost %d ms", nFiles,
            System.currentTimeMillis() - start));
}

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

public void testToJsonOnInheritedClassOutput() throws Exception {
    SpecialPerson[] spa = new SpecialPerson[TEST_SIZE];
    for (int i = 0; i < TEST_SIZE; i++) {
        spa[i] = new SpecialPerson(String.valueOf(i), "robot", "nonsense");
    }/*from ww  w  . ja  v a  2s  .  c o  m*/
    Runtime r = Runtime.getRuntime();
    String[] output = new String[TEST_SIZE];
    r.gc();
    long memstart = r.totalMemory() - r.freeMemory();
    long startOutput = System.currentTimeMillis();
    for (int i = 0; i < TEST_SIZE; i++) {
        output[i] = ((JSONObject) beanJsonConverter.convertToJson(spa[i])).toString();
    }
    long endOutput = System.currentTimeMillis();
    long memend = r.totalMemory() - r.freeMemory();
    String[] serializeOutput = new String[TEST_SIZE];
    char[] source = output[0].toCharArray();
    r.gc();

    long stringsizeStart = r.totalMemory() - r.freeMemory();

    for (int i = 0; i < TEST_SIZE; i++) {
        serializeOutput[i] = new String(source);
    }
    long stringsizeEnd = r.totalMemory() - r.freeMemory();

    log.info("ORG JSON Lib Output " + average(startOutput, endOutput, TEST_SIZE) + " ms/conversion, "
            + (average(memstart, memend, TEST_SIZE) - average(stringsizeStart, stringsizeEnd, TEST_SIZE))
            + " heap bytes/conversion, output packet consumed on average "
            + average(stringsizeStart, stringsizeEnd, TEST_SIZE) + " for a string length of "
            + output[0].length());
    log.info("Output Was [" + output[0] + ']');
}

From source file:org.sakaiproject.assignment.impl.AssignmentServiceTest.java

/**
 * /*from  w  ww.  jav a2  s.  c om*/
 * test the zip routine without/with flushing for 5 times
 *
 */
public void testZipSubmissionsWithoutFlushing() {
    if (testZipFunction) {
        System.out.println("student number = " + userNumber);
        System.out.println("attachment size = " + attachmentSize + "KB");
        System.gc();

        for (int index = 1; index <= testNumber; index++) {
            Random ran = new Random();
            boolean flushing = ran.nextBoolean();

            Runtime r = Runtime.getRuntime();
            System.out.println("with flushing = " + flushing);
            long mBefore = r.freeMemory();
            long tBefore = System.currentTimeMillis();

            zipWithFlushing(flushing);
            long mAfter = r.freeMemory();
            long tAfter = System.currentTimeMillis();
            System.out.println("free memory before invoke " + mBefore + " after " + mAfter);
            System.out.println("minute time used " + (tAfter - tBefore) / (1000.0 * 60.0));
            System.out.println("percent  " + (mBefore - mAfter) * 100 / (mBefore * 1.0));
            System.out.println("*************");
            // gc
            System.gc();
        }
    }
}

From source file:alluxio.util.JvmPauseMonitor.java

private String getMemoryInfo() {
    Runtime runtime = Runtime.getRuntime();
    return "max memory = " + runtime.maxMemory() / (1024 * 1024) + "M total memory = "
            + runtime.totalMemory() / (1024 * 1024) + "M free memory = " + runtime.freeMemory() / (1024 * 1024)
            + "M";
}

From source file:com.ettrema.zsync.IntegrationTests.java

/**
 * Creates the zsync File for servercopy, and saves it to a File with name fileName
 * @param fileName The name of the file in which to save the zsync data
 * @param blocksize The block size to use in MetaFileMaker
 * @return The created zsync File/*from ww w . jav  a  2s . c om*/
 * @throws FileNotFoundException
 */
private File createMetaFile(String fileName, int blocksize, File serverFile) throws FileNotFoundException {
    System.out.println("---------------- createMetaFile -------------------");

    System.gc();
    Runtime rt = Runtime.getRuntime();
    startUsed = rt.totalMemory() - rt.freeMemory();

    MetaFileMaker mkr = new MetaFileMaker();
    File zsfile = mkr.make(null, blocksize, serverFile);
    System.gc();
    System.out.println("Memory stats: " + formatBytes(rt.maxMemory()) + " - " + formatBytes(rt.totalMemory())
            + " - " + formatBytes(rt.freeMemory()));
    long endUsed = (rt.totalMemory() - rt.freeMemory());
    System.out.println("Start used memory: " + formatBytes(startUsed) + " end used memory: "
            + formatBytes(endUsed) + " - delta: " + formatBytes(endUsed - startUsed));

    File dest = new File(filepath + fileName);
    if (dest.exists()) {
        if (!dest.delete()) {
            throw new RuntimeException("Failed to delete previous meta file: " + dest.getAbsolutePath());
        }
    }
    System.out.println("rename meta file to: " + dest.getAbsolutePath());
    if (!zsfile.renameTo(dest)) {
        throw new RuntimeException("Failed to rename to: " + dest.getAbsolutePath());
    }
    System.out.println("Created meta file of size: " + formatBytes(dest.length())
            + " from source file of size: " + formatBytes(serverFile.length()));
    System.out.println("");
    return dest;
}

From source file:org.openflamingo.web.util.VersionConfigurer.java

@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
    Log4jWebConfigurer.initLogging(servletContextEvent.getServletContext());

    Properties properties = new Properties();
    ServletContext context = servletContextEvent.getServletContext();
    InputStream inputStream = null;
    try {// w  w w .  j  a  va 2 s .co m
        inputStream = context.getResourceAsStream("/WEB-INF/version.properties");
        properties.load(inputStream);
    } catch (Exception ex) {
        throw new IllegalArgumentException("Cannot load a '/WEB/INF/version.properties' file.", ex);
    } finally {
        IOUtils.closeQuietly(inputStream);
    }

    StringBuilder builder = new StringBuilder();

    printHeader(builder, "Application Information");
    Properties appProps = new Properties();
    appProps.put("Application", "Flamingo Workflow Engine");
    appProps.put("Version", properties.get("version"));
    appProps.put("Build Date", properties.get("build.timestamp"));
    appProps.put("Build Number", properties.get("build.number"));
    appProps.put("Revision Number", properties.get("revision.number"));
    appProps.put("Build Key", properties.get("build.key"));

    if (context != null) {
        appProps.put("Application Server", context.getServerInfo() + " - Servlet API "
                + context.getMajorVersion() + "." + context.getMinorVersion());
    }

    Properties systemProperties = System.getProperties();
    appProps.put("Java Version", systemProperties.getProperty("java.version", UNKNOWN) + " - "
            + systemProperties.getProperty("java.vendor", UNKNOWN));
    appProps.put("Current Working Directory", systemProperties.getProperty("user.dir", UNKNOWN));

    print(builder, appProps);

    Properties memPros = new Properties();
    final Runtime rt = Runtime.getRuntime();
    final long maxMemory = rt.maxMemory() / MEGA_BYTES;
    final long totalMemory = rt.totalMemory() / MEGA_BYTES;
    final long freeMemory = rt.freeMemory() / MEGA_BYTES;
    final long usedMemory = totalMemory - freeMemory;

    memPros.put("Maximum Allowable Memory", maxMemory + "MB");
    memPros.put("Total Memory", totalMemory + "MB");
    memPros.put("Free Memory", freeMemory + "MB");
    memPros.put("Used Memory", usedMemory + "MB");

    print(builder, memPros);

    printHeader(builder, "Java System Properties");
    Properties sysProps = new Properties();
    for (final Map.Entry<Object, Object> entry : systemProperties.entrySet()) {
        sysProps.put(entry.getKey(), entry.getValue());
    }

    print(builder, sysProps);

    printHeader(builder, "System Environments");
    Map<String, String> getenv = System.getenv();
    Properties envProps = new Properties();
    Set<String> strings = getenv.keySet();
    for (String key : strings) {
        String message = getenv.get(key);
        envProps.put(key, message);
    }

    print(builder, envProps);

    logger.info("=================================================");
    logger.info(" Flamingo Web Services starting...");
    logger.info("=================================================\n{}", builder.toString());
}

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.
 * /*w w w.ja v  a 2s  .  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;
}