Obtaining Runtime Information

The java.lang.Runtime class is part of the java.lang package, and it provides methods to interact with the Java runtime environment. It is a singleton class, meaning only one instance of it can be obtained through the getRuntime() method. This class is useful for managing system resources, executing processes, and obtaining runtime information such as memory usage, available processors, and garbage collection.

Key Methods of the Runtime Class

import java.io.IOException;

public class RuntimeInfoExample {
    public static void main(String[] args) {
        // Get the runtime instance
        Runtime runtime = Runtime.getRuntime();

        System.out.println("Available Processors: " + runtime.availableProcessors());
        System.out.println("Free Memory: " + runtime.freeMemory() + " bytes");
        System.out.println("Total Memory: " + runtime.totalMemory() + " bytes");
        System.out.println("Max Memory: " + runtime.maxMemory() + " bytes");

        // Execute a system command
        try {
            System.out.println("\nOpening Notepad...");
            Process process = runtime.exec("notepad");
            
            // Wait for the process to complete
            process.waitFor();
            
            System.out.println("Notepad closed.");
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }

        // Invoke garbage collection
        System.out.println("\nRunning Garbage Collector...");
        runtime.gc();

        System.out.println("Free Memory after GC: " + runtime.freeMemory() + " bytes");

        // Terminate the program
        System.out.println("\nExiting the program.");
        runtime.exit(0);
    }
}
/*
Available Processors: 8  
Free Memory: 10123456 bytes  
Total Memory: 16777216 bytes  
Max Memory: 536870912 bytes  

Opening Notepad...  
Notepad closed.  

Running Garbage Collector...  
Free Memory after GC: 12345678 bytes  

Exiting the program.
*/

The Runtime class is a powerful utility provided by Java to interact directly with the Java Virtual Machine (JVM) and the underlying operating system. Through this class, developers can:

  • Obtain vital runtime information like available processors, memory usage (free, total, and max memory),
  • Manage system resources by invoking garbage collection,
  • Execute system-level commands and processes,
  • Handle JVM lifecycle events such as program termination and shutdown hooks.

Because it follows the singleton design pattern, you access it through Runtime.getRuntime(), ensuring a single point of control over runtime operations.

In essence, the Runtime class acts as a bridge between your Java application and the environment it runs in, allowing you to monitor and influence JVM behavior and interact with the host OS efficiently.

Scroll to Top