Java Runtime Class in the java.lang Package

The Runtime class is used to objectify the execution environment. A Runtime object makes it possible to interact with the current operating system. It provides an interface to the system where the JVM is running, executes operating-system-based programs that are not Java classes, and provides information about the operating system.

Main Runtime Methods

Method Description
Process exec(String command) Executes the command and returns a reference to the executed process.
static Runtime getRuntime() Returns a reference to the Runtime object.
void exit(int status) Terminates the JVM while returning the status value.
long freeMemory() Returns the amount of memory available to the JVM in bytes.
long totalMemory() Returns the total memory used by the JVM.
long maxMemory() Returns the maximum amount of memory the JVM can use.

Runtime Examples

Example 1)

package com.devkuma.tutorial.java.lang;

public class RuntimeClass {

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

        long totalMemory = runtime.totalMemory();
        long freeMemory = runtime.freeMemory();
        long usedMemory = totalMemory - freeMemory;

        System.out.println("Total Memory : " + totalMemory);
        System.out.println("Free Memory : " + freeMemory);
        System.out.println("Used Memory : " + usedMemory);
    }
}

The execution result is as follows.

Total Memory : 128974848
Free Memory : 126929960
Used Memory : 2044888

Example 2) In the example below, write only the code for the relevant OS. If all of them are executed, an error occurs.

package com.devkuma.tutorial.javalang;

import java.io.IOException;

public class RuntimeClass1 {

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

        // Execute the command below for Mac.
        try {
            runtime.exec("open /Applications/Contacts.app");
        } catch (IOException e) {
            System.err.println("Error executing Contacts.");
        }

        // Execute the command below for linux.
        try {
            runtime.exec("gedit");
        } catch (IOException e) {
            System.err.println("Error executing gedit.");
        }

        // Execute the command below for windows.
        try {
            runtime.exec("calc.exe");
        } catch (IOException e) {
            System.err.println("Error executing calc.");
        }
    }
}

When executed, the application program appropriate for each OS will run. The execution result is omitted.

References

http://itmore.tistory.com/entry/Runtime-%ED%81%B4%EB%9E%98%EC%8A%A4