Java Runtime getRuntime() Method with Examples
Last Updated :
24 Oct, 2023
In Java, the Runtime class allows you to interact with the runtime environment of your application. One of the essential methods provided by this class is getRuntime(). This method returns the runtime object associated with the current Java application. With this object, you can access information about the runtime environment, execute system commands, manage processes, and more.
Java Runtime getRuntime() Method
The Runtime.getRuntime() method is a static method that retrieves the runtime object for the current Java application. This object allows you to access various aspects of the application’s runtime environment, such as executing system commands, managing processes, and querying memory usage.
Syntax:
public static Runtime getRuntime()
Example of Java Runtime getRuntime()
Now, let’s explore some practical examples of using the runtime object:
Java
import java.io.IOException;
public class GfgRuntimeExample {
public static void main(String[] args)
{
Runtime runtime = Runtime.getRuntime();
try {
Process process = runtime.exec(
int exitCode = process.waitFor();
System.out.println(
"Example 1: Executing System Command" );
System.out.println( "Exit Code: " + exitCode);
}
catch (IOException | InterruptedException e) {
e.printStackTrace();
}
int processors = runtime.availableProcessors();
System.out.println(
"\nExample 2: Retrieving Available Processors" );
System.out.println( "Available Processors: "
+ processors);
long totalMemory = runtime.totalMemory();
long freeMemory = runtime.freeMemory();
long totalMemoryMB = totalMemory / ( 1024 * 1024 );
long freeMemoryMB = freeMemory / ( 1024 * 1024 );
System.out.println(
"\nExample 3: Querying Total and Free Memory" );
System.out.println( "Total Memory (MB): "
+ totalMemoryMB);
System.out.println( "Free Memory (MB): "
+ freeMemoryMB);
}
}
|
Output:
Example 1: Executing System Command
Exit Code: 0
Example 2: Retrieving Available Processors
Available Processors: 4
Example 3: Querying Total and Free Memory
Total Memory (MB): 123
Free Memory (MB): 78
Conclusion
The Runtime.getRuntime() method provides access to the runtime environment of your Java application. You can use it to execute system commands, manage processes, and retrieve information about system resources like available processors and memory usage.
Share your thoughts in the comments
Please Login to comment...