Why java.lang.Runtime is a Singleton in Java?

In Java, java.lang.Runtime is implemented on Singleton design pattern.

Runtime is the class that acts as an interface with the environment in which Java process is running. Runtime contains methods that can interact with the environment.

Like- totalmemory() method gives the total memory in JVM. maxMemory() method gives the maximum memory that JVM can use.

There is an exit() method to exit the Java process. We do not want multiple objects in JVM to have exit() method.

Similarly there is gc() method that can run the Garbage Collector. With only one copy of gc() method, we can ensure that no other object can run the Garbage Collector when one instance of GC is already running.

Due to all these reasons there is only one copy of Runtime in Java. To ensure single copy of Runtime, it is implemented as a Singleton in Java.

Leave a Reply

Your email address will not be published. Required fields are marked *