Java Lang Runtime

Every JavaLanguage application has a single instance of class Runtime that allows the application to interface with the environment in which the application is running. The current runtime can be obtained from the getRuntime method.

While JavaLanguage has many Singleton-like classes, java.lang.Runtime is a by-the-book example of a singleton.

  public class Runtime {
      private static Runtime currentRuntime = new Runtime();

/** * Returns the runtime object associated with the current Java application. * Most of the methods of class <code>Runtime</code> are instance * methods and must be invoked with respect to the current runtime object. * * @return the <code>Runtime</code> object associated with the current * Java application. */ public static Runtime getRuntime() { return currentRuntime; }

/** Don't let anyone else instantiate this class */ private Runtime() {}
'private static Runtime currentRuntime = new Runtime();' is a Java implementation of "Make the class itself responsible for keeping track of its sole instance." As those familiar with Java/C++ already know, the key word private means that only this class may access the field currentRuntime. The keyword static denotes that only one instance of particular field may exist.

The first method in the class goes on to implement, "There must be exactly one instance of a class, and it must be accessible to clients from a well-known access point." Both of these idioms are further reinforced by the privatization of the Runtime constructor, as the author notes in her comments.


CategoryJavaPlatform


EditText of this page (last edited June 14, 2004) or FindPage with title or text search