Singleton In JDK: java.lang.Runtime

Categories: Java; Tagged with: ; @ July 3rd, 2012 23:21

Some times we need write some Singleton class for some reasons, like we need a singleton to store application settings. btw, we need this singleton thread safe.

Here is a good example for open JDK:

/**
 * Every Java 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.
 * 

* An application cannot create its own instance of this class. * * @author unascribed * @see java.lang.Runtime#getRuntime() * @since JDK1.0 */ 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 Runtime are instance * methods and must be invoked with respect to the current runtime object. * * @return the Runtime object associated with the current * Java application. */ public static Runtime getRuntime() { return currentRuntime; } /** Don't let anyone else instantiate this class */ private Runtime() {}

 

http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/7-b147/java/lang/Runtime.java

The private static runtime instance will initialized when the class loaded by JVM, so thread safe is guaranteed by JVM class load mechanism.

<->



// Proudly powered by Apache, PHP, MySQL, WordPress, Bootstrap, etc,.