The Runtime class

The Runtime class in Java is part of the java.lang package and is a singleton class that provides a way to interface with the Java Virtual Machine (JVM) at runtime. It lets your program interact with the environment, such as memory management, executing system commands, or exiting the program.


🔑 Key Features of Runtime Class

  1. Singleton → You cannot create an instance using new Runtime().
    • You get the instance via: Runtime runtime = Runtime.getRuntime();
  2. Memory Management → You can check memory and request garbage collection:
    • totalMemory() → Total memory JVM has allocated.
    • freeMemory() → Available free memory.
    • gc() → Suggest garbage collection.
  3. Execute System Commands → Run external programs using exec().
  4. Terminate JVM → Exit the program with exit(status).

🔧 Example 1: Memory Management

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

        System.out.println("Total Memory: " + runtime.totalMemory());
        System.out.println("Free Memory: " + runtime.freeMemory());

        // Request garbage collection
        runtime.gc();
        System.out.println("After GC, Free Memory: " + runtime.freeMemory());
    }
}

🔧 Example 2: Executing System Commands

import java.io.*;

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

        try {
            Process process = runtime.exec("notepad"); // Opens Notepad (Windows)
            process.waitFor(); // Wait until the process is finished
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

🔧 Example 3: Exit JVM

public class RuntimeExitExample {
    public static void main(String[] args) {
        System.out.println("Program is ending...");
        Runtime.getRuntime().exit(0); // Terminates JVM
        System.out.println("This line will not execute");
    }
}

🔎 Key Methods of Runtime Class

MethodDescription
getRuntime()Returns the singleton Runtime instance
exit(int status)Terminates JVM with status code
gc()Suggests garbage collection
totalMemory()Total memory allocated by JVM
freeMemory()Free memory available
exec(String command)Executes a system command
availableProcessors()Number of processors available

✅ Summary:

  • Runtime allows you to interact with JVM and the system.
  • It’s useful for memory info, garbage collection, system commands, and terminating programs.
  • Since it’s a singleton, always access via Runtime.getRuntime().

Leave a Reply