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:com.nridge.core.base.std.Platform.java

/**
 * Create a log message containing JVM Heap Memory statistics.
 * <p>totalMemory(): Returns the total amount of memory in the
 * Java virtual machine. The value returned by this method may
 * vary over time, depending on the host environment. Note that
 * the amount of memory required to hold an object of any given
 * type may be implementation-dependent.</p>
 * <p>maxMemory(): Returns the maximum amount of memory that the
 * Java virtual machine will attempt to use. If there is no inherent
 * limit then the value Long.MAX_VALUE will be returned.</p>
 * <p>freeMemory(): Returns the amount of free memory in the Java
 * Virtual Machine. Calling the gc method may result in increasing
 * the value returned by freeMemory.</p>
 * <p>In reference to your question, maxMemory() returns the -Xmx value.
 * You may be wondering why there is a totalMemory() AND a maxMemory().
 * The answer is that the JVM allocates memory lazily.</p>
 *
 * @param aTitle Title to save with log entry.
 *
 * @return Log message.//from  www  . j a  va2  s  .  c o  m
 *
 * @see <a href="http://stackoverflow.com/questions/3571203/what-is-the-exact-meaning-of-runtime-getruntime-totalmemory-and-freememory">Runtime Memory</a>
 * @see <a href="http://www.mkyong.com/java/find-out-your-java-heap-memory-size/">Heap Memory</a>
 * @see <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Runtime.html">JavaDoc Runtime</a>
 */
public static String jvmLogMessage(String aTitle) {
    Runtime jvmRuntime = Runtime.getRuntime();

    if (StringUtils.isEmpty(aTitle))
        aTitle = "JVM";

    long maxMemory = jvmRuntime.maxMemory();
    long freeMemory = jvmRuntime.freeMemory();
    long totalMemory = jvmRuntime.totalMemory();
    long usedMemory = totalMemory - freeMemory;
    long availMemory = maxMemory - usedMemory;

    String logMsg = String.format("%s: Processors: %d, Mem Max: %s, Mem Total: %s, Mem Used: %s, Mem Avail: %s",
            aTitle, jvmRuntime.availableProcessors(), bytesToString(maxMemory), bytesToString(totalMemory),
            bytesToString(usedMemory), bytesToString(availMemory));
    return logMsg;
}

From source file:com.fizzed.rocker.ConstantPoolMain.java

static public void garbageCollectAndPrintMemory() {

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

    runtime.gc();/*  w w  w  .  j a v  a  2 s .  c om*/

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

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

    //Print free memory
    /**
    System.out.println("Free Memory:"
    + runtime.freeMemory());
             
    //Print total available memory
    System.out.println("Total Memory:" + runtime.totalMemory());
            
    //Print Maximum available memory
    System.out.println("Max Memory:" + runtime.maxMemory());
    */
}

From source file:com.fizzed.rocker.bin.ConstantPoolMain.java

static public void garbageCollectAndPrintMemory() {

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

    runtime.gc();//w ww  . j av  a2s.com

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

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

    //Print free memory
    /**
    System.out.println("Free Memory:"
    + runtime.freeMemory());
            
    //Print total available memory
    System.out.println("Total Memory:" + runtime.totalMemory());
            
    //Print Maximum available memory
    System.out.println("Max Memory:" + runtime.maxMemory());
    */
}

From source file:eu.stratosphere.nephele.instance.HardwareDescriptionFactory.java

/**
 * Returns the size of free memory in bytes available to the JVM.
 * //from ww w.ja v a 2s . c om
 * @return the size of the free memory in bytes available to the JVM or <code>-1</code> if the size cannot be
 *         determined
 */
private static long getSizeOfFreeMemory() {
    float fractionToUse = GlobalConfiguration.getFloat(ConfigConstants.TASK_MANAGER_MEMORY_FRACTION_KEY,
            ConfigConstants.DEFAULT_MEMORY_MANAGER_MEMORY_FRACTION);

    Runtime r = Runtime.getRuntime();
    long max = r.maxMemory();
    long total = r.totalMemory();
    long free = r.freeMemory();

    long available = max - total + free;
    return (long) (fractionToUse * available);
}

From source file:org.soitoolkit.commons.mule.util.MiscUtil.java

private static void printMemUsage() {
    int mb = 1024 * 1024;

    MemoryMXBean mxb = ManagementFactory.getMemoryMXBean();
    MemoryUsage hm = mxb.getHeapMemoryUsage();
    MemoryUsage nhm = mxb.getNonHeapMemoryUsage();
    //      int finalizable = mxb.getObjectPendingFinalizationCount();

    logger.trace("Heap Memory:  init/used/committed/max=" + hm.getInit() / mb + "/" + hm.getUsed() / mb + "/"
            + hm.getCommitted() / mb + "/" + hm.getMax() / mb);
    logger.trace("Non-Heap Mem: init/used/committed/max=" + nhm.getInit() / mb + "/" + nhm.getUsed() / mb + "/"
            + nhm.getCommitted() / mb + "/" + nhm.getMax() / mb);
    //                 logger.trace("finalizable: " + finalizable);

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

    logger.trace("Used/Free/Total/Max:"
            //Print used memory
            + (runtime.totalMemory() - runtime.freeMemory()) / mb + "/"

            //Print free memory
            + runtime.freeMemory() / mb + "/"

            //Print total available memory
            + runtime.totalMemory() / mb + "/"

            //Print Maximum available memory
            + runtime.maxMemory() / mb);
}

From source file:org.apache.solr.handler.admin.SystemInfoHandler.java

/**
 * Get JVM Info - including memory info//from   ww w  .j a  v a 2 s  .  c om
 */
public static SimpleOrderedMap<Object> getJvmInfo() {
    SimpleOrderedMap<Object> jvm = new SimpleOrderedMap<Object>();
    jvm.add("version", System.getProperty("java.vm.version"));
    jvm.add("name", System.getProperty("java.vm.name"));

    Runtime runtime = Runtime.getRuntime();
    jvm.add("processors", runtime.availableProcessors());

    long used = runtime.totalMemory() - runtime.freeMemory();
    // not thread safe, but could be thread local
    DecimalFormat df = new DecimalFormat("#.#");
    double percentUsed = ((double) (used) / (double) runtime.maxMemory()) * 100;

    SimpleOrderedMap<Object> mem = new SimpleOrderedMap<Object>();
    mem.add("free", humanReadableUnits(runtime.freeMemory(), df));
    mem.add("total", humanReadableUnits(runtime.totalMemory(), df));
    mem.add("max", humanReadableUnits(runtime.maxMemory(), df));
    mem.add("used", humanReadableUnits(used, df) + " (%" + df.format(percentUsed) + ")");
    jvm.add("memory", mem);

    // JMX properties -- probably should be moved to a different handler
    SimpleOrderedMap<Object> jmx = new SimpleOrderedMap<Object>();
    try {
        RuntimeMXBean mx = ManagementFactory.getRuntimeMXBean();
        jmx.add("bootclasspath", mx.getBootClassPath());
        jmx.add("classpath", mx.getClassPath());

        // the input arguments passed to the Java virtual machine
        // which does not include the arguments to the main method.
        jmx.add("commandLineArgs", mx.getInputArguments());
        // a map of names and values of all system properties.
        //jmx.add( "SYSTEM PROPERTIES", mx.getSystemProperties());

        jmx.add("startTime", new Date(mx.getStartTime()));
        jmx.add("upTimeMS", mx.getUptime());
    } catch (Exception e) {
        log.warn("Error getting JMX properties", e);
    }
    jvm.add("jmx", jmx);
    return jvm;
}

From source file:io.bitsquare.common.util.Utilities.java

public static void printSystemLoad() {
    Runtime runtime = Runtime.getRuntime();
    long free = runtime.freeMemory() / 1024 / 1024;
    long total = runtime.totalMemory() / 1024 / 1024;
    long used = total - free;
    log.info("System load (no. threads/used memory (MB)): " + Thread.activeCount() + "/" + used);
}

From source file:org.eclipse.wb.internal.core.editor.errors.report2.EnvironmentFileReportInfo.java

private static String createContents(IProject project) {
    String c = "";
    c += "Product Name: " + BrandingUtils.getBranding().getProductName() + CR;
    c += "Product Version: " + ProductInfo.getProduct().getVersion() + "[" + ProductInfo.getProduct().getBuild()
            + "]" + CR;
    c += "Installation Path: " + getInstallationPath() + CR;
    c += "Eclipse Version: " + PlatformInfo.getEclipseVersion().toString() + CR;
    c += "Eclipse Build Name: " + PlatformInfo.getEclipseBuildName() + CR;
    c += "Eclipse Build ID: " + PlatformInfo.getEclipseBuildId() + CR;
    c += "IDE Name: " + PlatformInfo.getIDEName() + CR;
    c += "IDE Version: " + PlatformInfo.getIDEVersionString() + CR;
    c += "IDE NL: " + PlatformInfo.getIDENL() + CR;
    c += "Eclipse Commands: " + StringUtils.replaceChars(getSystemProperty("eclipse.commands"), "\n\r", " ")
            + CR;/*w  ww .  ja  v  a  2 s .  co m*/
    c += "Eclipse VM: " + getSystemProperty("eclipse.vm") + CR;
    c += "Eclipse VM Args: " + getSystemProperty("eclipse.vmargs") + CR;
    c += "OS Name: " + getSystemProperty("os.name") + CR;
    c += "OS Arch: " + getSystemProperty("os.arch") + CR;
    c += "OS Version: " + getSystemProperty("os.version") + CR;
    String linuxDescription = getLinuxDescription();
    if (!StringUtils.isEmpty(linuxDescription)) {
        c += "Linux Description: " + linuxDescription + CR;
    }
    String m_mozillaResult = tryCreateMozilla();
    if (!StringUtils.isEmpty(m_mozillaResult)) {
        c += "Browser Creation Result: " + m_mozillaResult + CR;
    }
    Runtime runtime = Runtime.getRuntime();
    c += "Available Processors: " + runtime.availableProcessors() + CR;
    c += "Memory Max: " + runtime.maxMemory() + CR;
    c += "Memory Total: " + runtime.totalMemory() + CR;
    c += "Memory Free: " + runtime.freeMemory() + CR;
    c += "Java Vendor: " + getSystemProperty("java.vendor") + CR;
    c += "Java Version: " + getSystemProperty("java.version") + CR;
    c += "Java Library Path: " + CR + getSystemProperty("java.library.path") + CR;
    c += "Project Class Path: " + CR + getClassPath(project) + CR;
    return c;
}

From source file:org.apache.axiom.attachments.impl.PartFactory.java

/**
 * This method checks the configured threshold and
 * the current runtime information.  If it appears that we could
 * run out of memory, the threshold is reduced.
 * //  w w w . j  a  v a2 s .co m
 * This method allows the user to request a much larger threshold without 
 * fear of running out of memory.  Using a larger in memory threshold generally 
 * results in better throughput.
 * 
 * @param configThreshold
 * @param inflight
 * @return threshold
 */
private static int getRuntimeThreshold(int configThreshold, int inflight) {

    // Determine how much free memory is available
    Runtime r = Runtime.getRuntime();
    long totalmem = r.totalMemory();
    long maxmem = r.maxMemory();
    long freemem = r.freeMemory();

    // @REVIEW
    // If maximum is not defined...limit to 1G
    if (maxmem == java.lang.Long.MAX_VALUE) {
        maxmem = 1024 * 1024 * 1024;
    }

    long availmem = maxmem - (totalmem - freemem);

    // Now determine the dynamic threshold
    int dynamicThreshold = (int) availmem / (THRESHOLD_FACTOR * inflight);

    // If it appears that we might run out of memory with this
    // threshold, reduce the threshold size.
    if (dynamicThreshold < configThreshold) {
        if (log.isDebugEnabled()) {
            log.debug("Using Runtime Attachment File Threshold " + dynamicThreshold);
            log.debug("maxmem   = " + maxmem);
            log.debug("totalmem = " + totalmem);
            log.debug("freemem  = " + freemem);
            log.debug("availmem = " + availmem);
        }

    } else {
        dynamicThreshold = configThreshold;
        if (log.isDebugEnabled()) {
            log.debug("Using Configured Attachment File Threshold " + configThreshold);
            log.debug("maxmem   = " + maxmem);
            log.debug("totalmem = " + totalmem);
            log.debug("freemem  = " + freemem);
            log.debug("availmem = " + availmem);
        }
    }
    return dynamicThreshold;
}

From source file:com.weibo.api.motan.util.StatsUtil.java

public static String memoryStatistic() {
    Runtime runtime = Runtime.getRuntime();

    double freeMemory = (double) runtime.freeMemory() / (1024 * 1024);
    double maxMemory = (double) runtime.maxMemory() / (1024 * 1024);
    double totalMemory = (double) runtime.totalMemory() / (1024 * 1024);
    double usedMemory = totalMemory - freeMemory;
    double percentFree = ((maxMemory - usedMemory) / maxMemory) * 100.0;

    double percentUsed = 100 - percentFree;

    DecimalFormat mbFormat = new DecimalFormat("#0.00");
    DecimalFormat percentFormat = new DecimalFormat("#0.0");

    StringBuilder sb = new StringBuilder();
    sb.append(mbFormat.format(usedMemory)).append("MB of ").append(mbFormat.format(maxMemory)).append(" MB (")
            .append(percentFormat.format(percentUsed)).append("%) used");
    return sb.toString();
}