Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

Runtime.getRuntime()

Returns the Runtime object of the current JVM: memory, processor count, shutdown hooks.

Available since: Java 1.0

Syntax

public static Runtime getRuntime()

Return value

RuntimeThe single Runtime object of this program.

Examples

Processors and memory (the values depend on the machine and JVM settings):

void main() {
    Runtime rt = Runtime.getRuntime();
    long mb = 1024 * 1024;
 
    IO.println("Processors: " + rt.availableProcessors());
    IO.println("Max memory: " + rt.maxMemory() / mb + " MB");
    IO.println("Total: " + rt.totalMemory() / mb + " MB");
    IO.println("Free: " + rt.freeMemory() / mb + " MB");
}

Output:

Processors: 16
Max memory: 4080 MB
Total: 258 MB
Free: 213 MB

Used memory is totalMemory() - freeMemory(). It grows when the program creates objects:

long usedMb() {
    Runtime rt = Runtime.getRuntime();
    return (rt.totalMemory() - rt.freeMemory()) / (1024 * 1024);
}
 
void main() {
    IO.println("Before: " + usedMb() + " MB");
    int[] big = new int[50_000_000];
    IO.println("After: " + usedMb() + " MB");
    IO.println(big.length);
}

Output:

Before: 44 MB
After: 195 MB
50000000

Notes

maxMemory() is the heap limit (set with -Xmx, for example java -Xmx512m Main.java), totalMemory() is how much the JVM has already taken from the system, and freeMemory() is the free part of it. The numbers are approximate: the garbage collector frees memory when it decides to, and System.gc() is only a request. availableProcessors() is handy for choosing a thread pool size. addShutdownHook(thread) registers code that runs when the program terminates.

See also

  • System.nanoTime() — Returns a high-resolution timer value in nanoseconds — for measuring durations. See also currentTimeMillis().
  • System.exit() — Terminates the program immediately with the given exit code.
  • Thread — A thread of execution that lets a program do several things at once.

Related recipes

In the tutorial

  • Memory and garbage collection — How Java works with memory — the stack and the heap, references, garbage collection, memory leaks through static collections and listeners, OutOfMemoryError and StackOverflowError, the G1 and ZGC collectors.

Thanks for reading!

Donate to the site — we work hard for you.