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:eu.stratosphere.nephele.instance.HardwareDescriptionFactory.java

/**
 * Returns the size of free memory in bytes available to the JVM.
 * /*from   w  w  w  .java  2 s .  c o m*/
 * @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:com.fizzed.rocker.bin.ConstantPoolMain.java

static public void garbageCollectAndPrintMemory() {

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

    runtime.gc();//www .j a v  a 2s .  c o  m

    //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:org.tranche.logs.LogUtil.java

/**
 * //w  w  w . j a v a  2 s .  c om
 * @return
 */
public static final String getEnvironmentDump() {
    StringBuffer buf = new StringBuffer();
    buf.append("Build: @buildNumber" + "\n");
    try {
        buf.append("Internet host/address: " + java.net.InetAddress.getLocalHost() + "\n");
    } catch (Exception e) {
    }
    Runtime rt = Runtime.getRuntime();
    long fm = rt.freeMemory();
    long tm = rt.totalMemory();
    long mm = rt.maxMemory();
    buf.append("Memory: ");
    buf.append("\n");
    buf.append("    Free: " + TextUtil.formatBytes(fm));
    buf.append("\n");
    buf.append("    Used: " + TextUtil.formatBytes(tm - fm));
    buf.append("\n");
    buf.append("    Total: " + TextUtil.formatBytes(tm));
    buf.append("\n");
    buf.append("    Maximum:" + TextUtil.formatBytes(mm));
    buf.append("\n" + "\n" + "\n");
    return buf.toString();
}

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.
 * /*from   w ww. ja va 2 s  .c o 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: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;/*from   w  w w . j  a v a2 s .c om*/
    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.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: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.//  w w  w . j  ava2  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:org.apache.solr.handler.admin.SystemInfoHandler.java

/**
 * Get JVM Info - including memory info/* w w w. jav  a  2 s .co m*/
 */
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:org.apache.hadoop.hdfs.server.namenode.Namenode2Agent.java

private static void startup() throws Exception {
    System.setProperty("PID", SystemUtils.getPid());

    try {/* ww w  .  j a v  a 2 s. c  o  m*/
        Log4jConfigurer.initLogging(System.getProperty("location"),
                Long.parseLong(System.getProperty("refreshInterval")));
    } catch (Exception ex) {
        System.out.println("Flamingo 2 :: Cannot load Log4J configuration file. Use Resource Manager Log4J.");
    }

    StringBuilder builder = new StringBuilder();

    LOG.info("============================================================\n"
            + "Now starting Flamingo 2 - Namenode 2 Agent (" + SystemUtils.getPid() + ") ....\n"
            + "============================================================");

    builder.append(
            "    ________                _                      __  __          __                     ___                    __ \n"
                    + "   / ____/ /___ _____ ___  (_)___  ____ _____     / / / /___ _____/ /___  ____  ____     /   | ____ ____  ____  / /_\n"
                    + "  / /_  / / __ `/ __ `__ \\/ / __ \\/ __ `/ __ \\   / /_/ / __ `/ __  / __ \\/ __ \\/ __ \\   / /| |/ __ `/ _ \\/ __ \\/ __/\n"
                    + " / __/ / / /_/ / / / / / / / / / / /_/ / /_/ /  / __  / /_/ / /_/ / /_/ / /_/ / /_/ /  / ___ / /_/ /  __/ / / / /_  \n"
                    + "/_/   /_/\\__,_/_/ /_/ /_/_/_/ /_/\\__, /\\____/  /_/ /_/\\__,_/\\__,_/\\____/\\____/ .___/  /_/  |_\\__, /\\___/_/ /_/\\__/  \n"
                    + "                                /____/                                      /_/             /____/                  ");

    SortedProperties properties = new SortedProperties();
    InputStream is = ResourceUtils.getResource("classpath:/version.properties").getInputStream();
    properties.load(is);
    is.close();

    printHeader(builder, "Application Information");
    SortedProperties appProps = new SortedProperties();
    appProps.put("Application", "Flamingo Hadoop Namenode 2 Monitoring Agent");
    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"));

    SortedProperties systemProperties = new SortedProperties();
    systemProperties.putAll(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);

    printHeader(builder, "Hadoop Information");

    SortedProperties hadoopProps = new SortedProperties();
    hadoopProps.put("Version", VersionInfo.getVersion()); // FIXME
    hadoopProps.put("Build Version", VersionInfo.getBuildVersion());

    print(builder, hadoopProps);

    printHeader(builder, "JVM Heap Information");

    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("Total Memory", totalMemory + "MB");
    memPros.put("Maximum Allowable Memory", maxMemory + "MB");
    memPros.put("Used Memory", usedMemory + "MB");
    memPros.put("Free Memory", freeMemory + "MB");

    print(builder, memPros);

    printHeader(builder, "Java System Properties");
    SortedProperties sysProps = new SortedProperties();
    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();
    SortedProperties envProps = new SortedProperties();
    Set<String> strings = getenv.keySet();
    for (String key : strings) {
        String message = getenv.get(key);
        envProps.put(key, message);
    }

    print(builder, envProps);

    /*
            LogbackConfigurer.initLogging("classpath:/logback.xml");
    */

    System.out.println(builder.toString());

    System.out.println(
            "================================================================================================");
    System.out.println(" Flamingo Hadoop Namenode 2 Monitoring Agent starting... ("
            + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + ")");
    System.out.println(
            "================================================================================================");
}

From source file:jfs.sync.encryption.JFSEncryptedStream.java

public static OutputStream createOutputStream(long compressionLimit, OutputStream baseOutputStream, long length,
        Cipher cipher) throws IOException {
    OutputStream result = null;/*from  ww  w  . j a  v  a 2s.  c om*/
    Runtime runtime = Runtime.getRuntime();
    long freeMem = runtime.totalMemory() / SPACE_RESERVE;
    if (length >= freeMem) {
        if (log.isWarnEnabled()) {
            log.warn("JFSEncryptedStream.createOutputStream() GC " + freeMem + "/" + runtime.maxMemory());
        } // if
        runtime.gc();
        freeMem = runtime.totalMemory() / SPACE_RESERVE;
    } // if
    if ((length < compressionLimit) && (length < freeMem)) {
        result = new JFSEncryptedStream(baseOutputStream, cipher);
    } else {
        if (length < freeMem) {
            if (log.isInfoEnabled()) {
                log.info("JFSEncryptedStream.createOutputStream() not compressing");
            } // if
        } else {
            if (log.isWarnEnabled()) {
                log.warn("JFSEncryptedStream.createOutputStream() due to memory constraints (" + length + "/"
                        + freeMem + ") not compressing");
            } // if
        } // if
        ObjectOutputStream oos = new ObjectOutputStream(baseOutputStream);
        oos.writeByte(COMPRESSION_NONE);
        oos.writeLong(length);
        oos.flush();
        result = baseOutputStream;
        if (cipher != null) {
            result = new CipherOutputStream(result, cipher);
        } // if
    } // if
    return result;
}