SrcForge

Lesson 50

Runtime Class

The Runtime class provides access to the JVM for memory info, process execution and shutdown management.

Java Track

Save progress as you learn.

61 lessons

Lesson content

The Runtime class belongs to java.lang and provides methods to interact directly with the JVM and operating system.

Definition List

  • Runtime Class: A Java class providing access to the Java Runtime Environment.
  • JVM: The runtime engine responsible for executing Java applications.
  • Garbage Collection: The automatic process of reclaiming unused memory.
  • Process: An external program executed by the operating system.
  • Singleton: Only one Runtime instance exists per JVM.

Getting the Runtime Instance

// Runtime follows Singleton pattern
Runtime runtime = Runtime.getRuntime();

Memory Relationship

Max Memory

Total Memory

Free Memory

Example: Java Runtime Class

package com.java.Multi_threading;

public class RuntimeExample {

    public static void main(String[] args) {

        Runtime runtime = Runtime.getRuntime();

        long freeMemory = runtime.freeMemory();
        long totalMemory = runtime.totalMemory();
        long maxMemory = runtime.maxMemory();

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

        try {
            Process process = runtime.exec("ls");
            int exitCode = process.waitFor();
            System.out.println("External process exited with code: " + exitCode);
        } catch (Exception e) {
            e.printStackTrace();
        }

        runtime.addShutdownHook(new Thread(() -> {
            System.out.println("Shutdown hook executed");
        }));

        // runtime.halt(0); // Commented out for safety
    }
}

Output

Free Memory: 15000000 bytes
Total Memory: 16252928 bytes
Max Memory: 259522560 bytes
External process exited with code: 0
Shutdown hook executed

Common Runtime Methods

// Memory info
runtime.freeMemory();       // Available memory in JVM
runtime.totalMemory();      // Total allocated memory
runtime.maxMemory();        // Maximum memory JVM can use

// System info
runtime.availableProcessors(); // Number of CPU cores

// Actions
runtime.gc();               // Request garbage collection
runtime.exec("ls");         // Execute an OS command
runtime.addShutdownHook(thread); // Register shutdown hook
runtime.halt(0);            // Force-terminate JVM immediately

Best Practices

  • Always use getRuntime() — Runtime cannot be instantiated directly.
  • Handle exceptions from exec() with try-catch.
  • Avoid excessive gc() calls; let the JVM manage collection.
  • Use platform-specific commands carefully across OS environments.
  • Always manage external processes and release resources properly.

FAQ

1. What is the Runtime class in Java?

A class that provides access to the JVM for memory management, process execution and shutdown hook registration.

2. How do you get the Runtime object?

Use Runtime.getRuntime() — it returns the single instance associated with the current JVM.

3. Can Runtime execute OS commands?

Yes. The exec() method runs external processes and returns a Process object for interaction.

Runtime follows the Singleton pattern — one instance per JVM.
Access it via Runtime.getRuntime().
freeMemory(), totalMemory(), maxMemory() expose JVM memory.
exec() runs OS commands and returns a Process object.
gc() requests GC — JVM decides when to run it.
availableProcessors() is useful for thread pool sizing.
halt() force-terminates JVM; shutdown hooks do NOT run.

Where Java is used

Java in real-world development

getRuntime()

Returns the single Runtime instance for the current JVM.

freeMemory()

Returns the amount of free memory currently available in the JVM.

exec()

Executes an external OS command and returns a Process object.

gc()

Requests garbage collection. The JVM decides whether to run it immediately.

availableProcessors()

Returns the number of CPU cores available to the JVM.

halt()

Force-terminates the JVM immediately. Shutdown hooks will not execute.

Prev: Shutdown HookBack to hub