What are Runtime.getRuntime().totalMemory() and freeMemory()?

runtime.getruntime().totalmemory() in mb
runtime.getruntime().freememory() unit
runtime.getruntime().get total heap memory()
runtime.getruntime().get current size()
runtime.totalmemory() returns the current process size.
runtime getruntime availableprocessors
runtime java
how to check memory usage in java program

I've been wondering what the exact meaning of Runtime.getRuntime().totalMemory(), Runtime.getRuntime().freeMemory(), and Runtime.getRuntime().maxMemory() is.

My understanding is, Runtime.getRuntime().totalMemory() returns the total memory my process is using. Is that correct?

How about freeMemory() and maxMemory()?

According to the API

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.

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.

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.

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. Lets say you start your Java process as such:

java -Xms64m -Xmx1024m Foo

Your process starts with 64mb of memory, and if and when it needs more (up to 1024m), it will allocate memory. totalMemory() corresponds to the amount of memory currently available to the JVM for Foo. If the JVM needs more memory, it will lazily allocate it up to the maximum memory. If you run with -Xms1024m -Xmx1024m, the value you get from totalMemory() and maxMemory() will be equal.

Also, if you want to accurately calculate the amount of used memory, you do so with the following calculation :

final long usedMem = totalMemory() - freeMemory();

Runtime (Java Platform SE 7 ), You can use Runtime.getRuntime.totalMemory() to get total memory from JVM which represents the current heap size of JVM which is a� Runtime#totalMemory – the memory that the JVM has allocated thus far. This isn’t necessarily what is in use or the maximum. Runtime#maxMemory – the maximum amount of memory that the JVM has been configured to use.

The names and values are confusing. If you are looking for the total free memory you will have to calculate this value by your self. It is not what you get from freeMemory();.

See the following guide:

Total designated memory, this will equal the configured -Xmx value:

Runtime.getRuntime().maxMemory();

Current allocated free memory, is the current allocated space ready for new objects. Caution this is not the total free available memory:

Runtime.getRuntime().freeMemory();

Total allocated memory, is the total allocated space reserved for the java process:

Runtime.getRuntime().totalMemory();

Used memory, has to be calculated:

usedMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();

Total free memory, has to be calculated:

freeMemory = Runtime.getRuntime().maxMemory() - usedMemory;

A picture may help to clarify:

How to get max memory, free memory and total memory in Java, getMax() ? 2- is Runtime.getRuntime().totalMemory() - Runtime.getRuntime(). freeMemory(); = memoryMXBean.getHeapMemoryUsage().getUsed()? 3- is� To obtain these values, use the totalMemory( ) and freeMemory( ) methods. The java.lang.Runtime.totalMemory() method 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.

To understand it better, run this following program (in jdk1.7.x) :

$ java -Xms1025k -Xmx1025k -XshowSettings:vm  MemoryTest

This will print jvm options and the used, free, total and maximum memory available in jvm.

public class MemoryTest {    
    public static void main(String args[]) {
                System.out.println("Used Memory   :  " + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) + " bytes");
                System.out.println("Free Memory   : " + Runtime.getRuntime().freeMemory() + " bytes");
                System.out.println("Total Memory  : " + Runtime.getRuntime().totalMemory() + " bytes");
                System.out.println("Max Memory    : " + Runtime.getRuntime().maxMemory() + " bytes");            
        }
}

Diff�rence between runtime.totalMemory() and , @Override public Status check() { Runtime runtime = Runtime.getRuntime(); long freeMemory = runtime.freeMemory(); long totalMemory = runtime. Teams. Q&A for Work. Stack Overflow for Teams is a private, secure spot for you and your coworkers to find and share information.

Codified version of all other answers (at the time of writing):

import java.io.*;

/**
 * This class is based on <a href="http://stackoverflow.com/users/2478930/cheneym">cheneym</a>'s
 * <a href="http://stackoverflow.com/a/18375641/253468">awesome interpretation</a>
 * of the Java {@link Runtime}'s memory query methods, which reflects intuitive thinking.
 * Also includes comments and observations from others on the same question, and my own experience.
 * <p>
 * <img src="/images/55220799-1.png" alt="Runtime's memory interpretation">
 * <p>
 * <b>JVM memory management crash course</b>:
 * Java virtual machine process' heap size is bounded by the maximum memory allowed.
 * The startup and maximum size can be configured by JVM arguments.
 * JVMs don't allocate the maximum memory on startup as the program running may never require that.
 * This is to be a good player and not waste system resources unnecessarily.
 * Instead they allocate some memory and then grow when new allocations require it.
 * The garbage collector will be run at times to clean up unused objects to prevent this growing.
 * Many parameters of this management such as when to grow/shrink or which GC to use
 * can be tuned via advanced configuration parameters on JVM startup.
 *
 * @see <a href="http://stackoverflow.com/a/42567450/253468">
 *     What are Runtime.getRuntime().totalMemory() and freeMemory()?</a>
 * @see <a href="http://www.oracle.com/technetwork/java/javase/memorymanagement-whitepaper-150215.pdf">
 *     Memory Management in the Sun Java HotSpot™ Virtual Machine</a>
 * @see <a href="http://docs.oracle.com/javase/8/docs/technotes/tools/windows/java.html">
 *     Full VM options reference for Windows</a>
 * @see <a href="http://docs.oracle.com/javase/8/docs/technotes/tools/unix/java.html">
 *     Full VM options reference for Linux, Mac OS X and Solaris</a>
 * @see <a href="http://www.oracle.com/technetwork/articles/java/vmoptions-jsp-140102.html">
 *     Java HotSpot VM Options quick reference</a>
 */
public class SystemMemory {

    // can be white-box mocked for testing
    private final Runtime runtime = Runtime.getRuntime();

    /**
     * <b>Total allocated memory</b>: space currently reserved for the JVM heap within the process.
     * <p>
     * <i>Caution</i>: this is not the total memory, the JVM may grow the heap for new allocations.
     */
    public long getAllocatedTotal() {
        return runtime.totalMemory();
    }

    /**
     * <b>Current allocated free memory</b>: space immediately ready for new objects.
     * <p>
     * <i>Caution</i>: this is not the total free available memory,
     * the JVM may grow the heap for new allocations.
     */
    public long getAllocatedFree() {
        return runtime.freeMemory();
    }

    /**
     * <b>Used memory</b>:
     * Java heap currently used by instantiated objects. 
     * <p>
     * <i>Caution</i>: May include no longer referenced objects, soft references, etc.
     * that will be swept away by the next garbage collection.
     */
    public long getUsed() {
        return getAllocatedTotal() - getAllocatedFree();
    }

    /**
     * <b>Maximum allocation</b>: the process' allocated memory will not grow any further.
     * <p>
     * <i>Caution</i>: This may change over time, do not cache it!
     * There are some JVMs / garbage collectors that can shrink the allocated process memory.
     * <p>
     * <i>Caution</i>: If this is true, the JVM will likely run GC more often.
     */
    public boolean isAtMaximumAllocation() {
        return getAllocatedTotal() == getTotal();
        // = return getUnallocated() == 0;
    }

    /**
     * <b>Unallocated memory</b>: amount of space the process' heap can grow.
     */
    public long getUnallocated() {
        return getTotal() - getAllocatedTotal();
    }

    /**
     * <b>Total designated memory</b>: this will equal the configured {@code -Xmx} value.
     * <p>
     * <i>Caution</i>: You can never allocate more memory than this, unless you use native code.
     */
    public long getTotal() {
        return runtime.maxMemory();
    }

    /**
     * <b>Total free memory</b>: memory available for new Objects,
     * even at the cost of growing the allocated memory of the process.
     */
    public long getFree() {
        return getTotal() - getUsed();
        // = return getAllocatedFree() + getUnallocated();
    }

    /**
     * <b>Unbounded memory</b>: there is no inherent limit on free memory.
     */
    public boolean isBounded() {
        return getTotal() != Long.MAX_VALUE;
    }

    /**
     * Dump of the current state for debugging or understanding the memory divisions.
     * <p>
     * <i>Caution</i>: Numbers may not match up exactly as state may change during the call.
     */
    public String getCurrentStats() {
        StringWriter backing = new StringWriter();
        PrintWriter out = new PrintWriter(backing, false);
        out.printf("Total: allocated %,d (%.1f%%) out of possible %,d; %s, %s %,d%n",
                getAllocatedTotal(),
                (float)getAllocatedTotal() / (float)getTotal() * 100,
                getTotal(),
                isBounded()? "bounded" : "unbounded",
                isAtMaximumAllocation()? "maxed out" : "can grow",
                getUnallocated()
        );
        out.printf("Used: %,d; %.1f%% of total (%,d); %.1f%% of allocated (%,d)%n",
                getUsed(),
                (float)getUsed() / (float)getTotal() * 100,
                getTotal(),
                (float)getUsed() / (float)getAllocatedTotal() * 100,
                getAllocatedTotal()
        );
        out.printf("Free: %,d (%.1f%%) out of %,d total; %,d (%.1f%%) out of %,d allocated%n",
                getFree(),
                (float)getFree() / (float)getTotal() * 100,
                getTotal(),
                getAllocatedFree(),
                (float)getAllocatedFree() / (float)getAllocatedTotal() * 100,
                getAllocatedTotal()
        );
        out.flush();
        return backing.toString();
    }

    public static void main(String... args) {
        SystemMemory memory = new SystemMemory();
        System.out.println(memory.getCurrentStats());
    }
}

java.lang.Runtime.totalMemory java code examples, TotalMemory () y freeMemory ()?. Me he estado preguntando cu�l es el significado exacto de Runtime.getRuntime (). TotalMemory () , Runtime. getRuntime (). Runtime#totalMemory - the memory that the JVM has allocated thus far. This isn't necessarily what is in use or the maximum. Runtime#maxMemory - the maximum amount of memory that the JVM has been configured to use.

Runtime#totalMemory - the memory that the JVM has allocated thus far. This isn't necessarily what is in use or the maximum.

Runtime#maxMemory - the maximum amount of memory that the JVM has been configured to use. Once your process reaches this amount, the JVM will not allocate more and instead GC much more frequently.

Runtime#freeMemory - I'm not sure if this is measured from the max or the portion of the total that is unused. I am guessing it is a measurement of the portion of total which is unused.

什么是Runtime.getRuntime()。totalMemory()和freeMemory , Runtime.getRuntime()。freeMemory();. 总分配内存,是为Java进程保留的总分配空间:. Runtime. freeMemory() + " bytes"); System.out.println("Total Memory : " + Runtime. totalMemory() and freeMemory()?</a> * @see <a� Every Java application has a single instance of class Runtime that allows the application to interface with the environment in which the application is running. The current runtime can be obtained from the getRuntime method.

�Qu� son Runtime.getRuntime (). TotalMemory () y freeMemory ()?, freeMemory() + " bytes"); System.out.println("Total Memory : " + Runtime. getRuntime(). totalMemory() and freeMemory()?</a> * @see <a href="http:// www. Free memory: 81915960 Free memory: 81353824 Just another guess: maybe it depends on the initial heap size parameter of the JVM, so that if the JVM starts with enough heap already ready to be used it doesn't need to allocate it before a certain threshold (it is the -Xms setting, you could trying increasing or decreasing it to see if something

Java Runtime.getRuntime().freeMemory() вопросы, Вызов System.gc() сначала сделает объем свободной / доступной памяти более надежным? Могу ли я There is insufficient memory for the Java Runtime Environment to continue. Native memory totalMemory() и freeMemory ()?. Java Runtime freeMemory() and totalMemory() method : Runtime runtime=Runtime.getRuntime(); System.out.println("Total Memory: "+runtime.totalMemory()); System.out

FreeMemory e Runtime.getRuntime (). MaxMemory () è. La mia comprensione è, Runtime.getRuntime().totalMemory() restituisce la memoria totale utilizzata dal mio processo.

Comments
  • The -Xmx value seems to directly affect the initial maxMemory() value however I have seen the reported maxMemory() increase by a small amount, perhaps ~1%, while the program is running.
  • How is this different from Debug.getNativeHeapFreeSize()?
  • @H2ONaCl yes, it might slightly change, because JVM's UseAdaptiveSizePolicy is enabled by default. And BTW: maxMemory() = Xmx - size of a single survivor space. Why? Because at the same time, only one survivor space can be used.
  • Is this different from Debug.getMemoryInfo()?
  • Note: Used memory may contain no longer referenced objects that will be swept away by the next GC.
  • @cheneym, free and unlocated memory will be occupied as the java byte code instructions will be processed by processor only if "Xmx - Usedmemory" is avlbl in machine. Xmx is like max capacity of ballon which could fill with air geting from avlbl air in machine itself, as soon it gets air, it will be filled and will blast once exceeds Xmx limit. But total freememory wont tell the actual avbl memory in machine for JVM, but just the nmbr.Is there Any way I could find out the actual avlbl memory in machine so that I could get to know whether rqd memory is avlbl or not for JVM remaning process ?