Java : Runtime with Examples

Runtime (Java SE 19 & JDK 19) API Examples.
You will find code examples on most Runtime methods.


Summary

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.

Class diagram

public class Main {
    public static void main(String[] args) {
        final var runtime = Runtime.getRuntime();

        final var large = new byte[200000000];
        System.out.println("use   = " + large.length / (1024 * 1024) + "MB");

        System.out.println("max   = " + runtime.maxMemory() / (1024 * 1024) + "MB");
        System.out.println("total = " + runtime.totalMemory() / (1024 * 1024) + "MB");
        System.out.println("free  = " + runtime.freeMemory() / (1024 * 1024) + "MB");
    }
}

// Result
// ↓
//use   = 190MB
//max   = 8184MB
//total = 512MB
//free  = 316MB

An example of starting Notepad on Windows.

final String[] command = {"notepad"};

final var runtime = Runtime.getRuntime();
final var process = runtime.exec(command);
System.out.println(process); // Process[pid=14796, exitValue="not exited"]

final var ret = process.waitFor();
System.out.println(ret); // 0

 ↓

Notepad


Methods

void addShutdownHook (Thread hook)

Registers a new virtual-machine shutdown hook.

public class Main {
    public static void main(String[] args) {
        System.out.println("main : start");

        final var hook = new Thread(() -> {
            System.out.println("Hook!");
        });

        final var runtime = Runtime.getRuntime();
        runtime.addShutdownHook(hook);

        if (args.length == 1 && "remove".equals(args[0])) {
            System.out.println("remove hook!");
            runtime.removeShutdownHook(hook);
        }

        System.out.println("main : end");
    }
}

// Result
// ↓
//> java Main
//main : start
//main : end
//Hook!
//
//> java Main remove
//main : start
//remove hook!
//main : end

int availableProcessors ()

Returns the number of processors available to the Java virtual machine.

final var runtime = Runtime.getRuntime();
System.out.println(runtime.availableProcessors()); // 8

Process exec (String command)

Deprecated. This method is error-prone and should not be used, the corresponding method exec(String[]) or ProcessBuilder should be used instead.

Deprecated.

Process exec (String[] cmdarray)

Executes the specified command and arguments in a separate process.

public class Exec {
    public static void main(String[] args) {
        System.out.println("TEST 1");
        System.out.println("TEST 2");
        System.out.println("TEST 3");
    }
}
public class Main {
    public static void main(String[] args) throws IOException, InterruptedException {
        System.out.println("main : start");

        final String[] cmdarray = {"java", "Exec"};
        final var runtime = Runtime.getRuntime();

        final var process = runtime.exec(cmdarray);
        try (final var reader = process.inputReader()) {
            reader.lines().forEach(System.out::println);
        }
        System.out.println("waitFor : " + process.waitFor());

        System.out.println("main : end");
    }
}

// Result
// ↓
//> java Main
//main : start
//TEST 1
//TEST 2
//TEST 3
//waitFor : 0
//main : end

Process exec (String[] cmdarray, String[] envp)

Executes the specified command and arguments in a separate process with the specified environment.

public class Exec {
    public static void main(String[] args) {
        System.out.println("env1=" + System.getenv("env1"));
        System.out.println("env2=" + System.getenv("env2"));
        System.out.println("env3=" + System.getenv("env3"));
    }
}
public class Main {
    public static void main(String[] args) throws IOException, InterruptedException {
        System.out.println("main : start");

        final String[] cmdarray = {"java", "Exec"};
        final String[] envp = {"env1=aaa", "env2=bbb", "env3=ccc"};

        final var runtime = Runtime.getRuntime();

        final var process = runtime.exec(cmdarray, envp);
        try (final var reader = process.inputReader()) {
            reader.lines().forEach(System.out::println);
        }
        System.out.println("waitFor : " + process.waitFor());

        System.out.println("main : end");
    }
}

// Result
// ↓
//> java Main
//main : start
//env1=aaa
//env2=bbb
//env3=ccc
//waitFor : 0
//main : end

Process exec (String[] cmdarray, String[] envp, File dir)

Executes the specified command and arguments in a separate process with the specified environment and working directory.

public class Exec {
    public static void main(String[] args) {
        System.out.println("user.dir=" + System.getProperty("user.dir"));
    }
}
public class Main {
    public static void main(String[] args) throws IOException, InterruptedException {
        System.out.println("main : start");

        final String[] cmdarray = {"java", "Exec"};
        final String[] envp = {"env1=aaa", "env2=bbb", "env3=ccc"};
        final var dir = Path.of("R:", "java-work", "dir");

        final var runtime = Runtime.getRuntime();

        final var process = runtime.exec(cmdarray, envp, dir.toFile());
        try (final var reader = process.inputReader()) {
            reader.lines().forEach(System.out::println);
        }
        System.out.println("waitFor : " + process.waitFor());

        System.out.println("main : end");
    }
}

// --- PowerShell ---
//PS R:\java-work> tree /F
//...
//R:.
//│  Main.class
//│  Main.java
//│
//└─dir
//        Exec.class
//        Exec.java
//
//PS R:\java-work> java Main
//main : start
//user.dir=R:\java-work\dir
//waitFor : 0
//main : end

Process exec (String command, String[] envp)

Deprecated. This method is error-prone and should not be used, the corresponding method exec(String[], String[]) or ProcessBuilder should be used instead.

Deprecated.

Process exec (String command, String[] envp, File dir)

Deprecated. This method is error-prone and should not be used, the corresponding method exec(String[], String[], File) or ProcessBuilder should be used instead.

Deprecated.

void exit (int status)

Terminates the currently running Java virtual machine by initiating its shutdown sequence.

public class Main {
    public static void main(String[] args) {
        System.out.println("main : start");

        final var hook = new Thread(() -> {
            System.out.println("Hook!");
        });

        final var runtime = Runtime.getRuntime();
        runtime.addShutdownHook(hook);

        if (args.length == 1) {
            switch (args[0]) {
                case "exit" -> {
                    System.out.println("exit");
                    runtime.exit(0);
                }
                case "halt" -> {
                    System.out.println("halt");
                    runtime.halt(0);
                }
            }
        }

        System.out.println("main : end");
    }
}

// Result
// ↓
//> java Main
//main : start
//main : end
//Hook!
//
//> java Main exit
//main : start
//exit
//Hook!
//
//> java Main halt
//main : start
//halt

long freeMemory ()

Returns the amount of free memory in the Java Virtual Machine.

public class Main {
    public static void main(String[] args) {
        final var runtime = Runtime.getRuntime();

        final var large = new byte[200000000];
        System.out.println("use   = " + large.length / (1024 * 1024) + "MB");

        System.out.println("max   = " + runtime.maxMemory() / (1024 * 1024) + "MB");
        System.out.println("total = " + runtime.totalMemory() / (1024 * 1024) + "MB");
        System.out.println("free  = " + runtime.freeMemory() / (1024 * 1024) + "MB");
    }
}

// Result
// ↓
//use   = 190MB
//max   = 8184MB
//total = 512MB
//free  = 316MB

void gc ()

Runs the garbage collector in the Java Virtual Machine.

Please see also :System.gc

final var runtime = Runtime.getRuntime();

var sb = new StringBuilder("abcd");
final var ref = new WeakReference<>(sb);

System.out.println(ref.get()); // abcd

sb = null;
runtime.gc();

System.out.println(ref.get()); // null

static Runtime getRuntime ()

Returns the runtime object associated with the current Java application.

Please see freeMemory().

void halt (int status)

Forcibly terminates the currently running Java virtual machine.

Please see exit(int status).

void load (String filename)

Loads the native library specified by the filename argument.

Please see also :System.load

public class JniSample {

    public native int sum(int a, int b);
}

For JNI (cpp)

JNIEXPORT jint JNICALL Java_JniSample_sum
(JNIEnv*, jobject, jint a, jint b) {

    return a + b;
}

Create a DLL and place it to the below.

R:\java-work\lib\JniSample.dll
public class JniMain {

    public static void main(String[] args) {

        final var libPath = Path.of("R:", "java-work", "lib", "JniSample.dll");
        System.out.println(libPath); // R:\java-work\lib\JniSample.dll

        final var runtime = Runtime.getRuntime();
        runtime.load(libPath.toString());

        final var sample = new JniSample();

        final var ret = sample.sum(100, 200);
        System.out.println(ret); // 300
    }
}

void loadLibrary (String libname)

Loads the native library specified by the libname argument.

Please see also :System.loadLibrary

public class JniSample {

    public native int sum(int a, int b);
}

For JNI (cpp)

JNIEXPORT jint JNICALL Java_JniSample_sum
(JNIEnv*, jobject, jint a, jint b) {

    return a + b;
}

Create a DLL and place it to the below.

R:\java-work\lib\JniSample.dll
public class JniMain {

    public static void main(String[] args) {

        final var runtime = Runtime.getRuntime();
        runtime.loadLibrary("JniSample");

        final var sample = new JniSample();

        final var ret = sample.sum(100, 200);
        System.out.println(ret); // 300
    }
}
java -D"java.library.path=R:\java-work\lib" JniMain

long maxMemory ()

Returns the maximum amount of memory that the Java virtual machine will attempt to use.

Please see freeMemory().

boolean removeShutdownHook (Thread hook)

De-registers a previously-registered virtual-machine shutdown hook.

Please see addShutdownHook(Thread hook).

void runFinalization ()

Deprecated, for removal: This API element is subject to removal in a future version. Finalization has been deprecated for removal.

Deprecated.

long totalMemory ()

Returns the total amount of memory in the Java virtual machine.

Please see freeMemory().

static Runtime.Version version ()

Returns the version of the Java Runtime Environment as a Runtime.Version.

final var version = Runtime.version();
System.out.println(version); // 19.0.2+7-44

Related posts

To top of page