Card 05/ 09

ExampleDifficulty: Intermediate1 min

Singleton in the Wild: Java's Runtime.getRuntime()

Every call returns the same Runtime, the one that describes the running Java process.

The JDK's java.lang.Runtime is a Singleton: there is one Java process running your program, so there is one Runtime object describing it, and Runtime.getRuntime() returns it. The listing checks that two calls return the same object, and lists the class's constructors to show how a second one is prevented.

java
import java.lang.reflect.Constructor;
import java.lang.reflect.Modifier;

public class SgRuntime {
    public static void main(String[] args) {
        Runtime first = Runtime.getRuntime();
        Runtime second = Runtime.getRuntime();
        System.out.println("same Runtime: " + (first == second));

        for (Constructor<?> constructor : Runtime.class.getDeclaredConstructors()) {
            System.out.println("constructor: " + Modifier.toString(constructor.getModifiers()) + " " + constructor.getName() + "()");
        }
    }
}
OutputRan with eclipse-temurin:21-jdk (Java 21.0.12)
same Runtime: true
constructor: private java.lang.Runtime()
Two calls, one object, and a constructor no other class can call.

Both calls return the same object, and the class's only constructor is private, as the output from OpenJDK 21 shows. Your code cannot write new Runtime(); it can only ask for the instance the JDK made. Through it you can read how many processors the machine has and how much memory the process holds, or register code to run when the process exits.

What this shares with the configuration example is the shape that identifies the pattern: the class controls its own creation, and every caller gets the same object through a static method. Runtime is also a fair use of the pattern. There genuinely is only one running process, and most of what the object reports is read rather than changed, so callers seldom affect one another through it.