The Java Runtime class is used to interact with the Java runtime environment. It provides methods to execute external processes, invoke garbage collection, and obtain information about total and free memory.
In a Java application, only one instance of the java.lang.Runtime class exists. This instance is shared by the entire application.
The Runtime.getRuntime() method is used to obtain this singleton instance of the Runtime class.
The Runtime class belongs to the java.lang package. Since this package is imported automatically by Java, no explicit import statement is required to use the Runtime class in a program.
The java.lang.Runtime class does not provide any public constructors. This is because the Runtime class follows the singleton design pattern.
An object of the Runtime class cannot be created using the new keyword. The only way to obtain its instance is by calling the Runtime.getRuntime() method, which returns the single Runtime instance associated with the Java application.
The following table lists the important methods of the Java Runtime class along with their descriptions.
| Method | Description |
|---|---|
| public static Runtime getRuntime() | returns the instance of Runtime class. |
| public void exit(int status) | terminates the current virtual machine. |
| public void addShutdownHook(Thread hook) | registers new hook thread. |
| public Process exec(String command)throws IOException | executes given command in a separate process. |
| public int availableProcessors() | returns no. of available processors. |
| public long freeMemory() | returns amount of free memory in JVM. |
| public long totalMemory() | returns amount of total memory in JVM. |
The following examples demonstrate how different methods of the Java Runtime class are used in real programs.
This example shows how to execute an external program using the exec() method.
This example demonstrates how to shut down the system using the shutdown command.
Here you can use -s switch to shutdown system, -r switch to restart system and -t switch to specify time delay.
This example shows how to shut down a Windows system by providing the full path of the shutdown command.
This example demonstrates how to restart the system using the Runtime class.
This example prints the number of processors available to the JVM.
This example shows how memory changes before and after garbage collection.
Output:
Total Memory: 100139008 Free Memory: 99474824 After creating 10000 instance, Free Memory: 99310552 After gc(), Free Memory: 100182832
We request you to subscribe our newsletter for upcoming updates.