A singleton is a class that only ever has one single instance. For more information on the Singleton design pattern, please refer to the Singleton topic in the Design Patterns tag.
Version ≥ Java SE 5 public enum Singleton { INSTANCE; public void execute (String arg) { // Perform operation here } }
Enums have private constructors, are final and provide proper serialization machinery. They are also very concise and lazily initialized in a thread safe manner.
The JVM provides a guarantee that enum values will not be instantiated more than once each, which gives the enum singleton pattern a very strong defense against reflection attacks.
What the enum pattern doesn't protect against is other developers physically adding more elements to the source code. Consequently, if you choose this implementation style for your singletons it is imperative that you very clearly document that no new values should be added to those enums.
This is the recommended way of implementing the singleton pattern, as explained by Joshua Bloch in Effective Java.
public class Singleton { private static final Singleton INSTANCE = new Singleton(); private Singleton() {} public static Singleton getInstance() { return INSTANCE; } }
It can be argued that this example is effectively lazy initialization. Section 12.4.1 of the Java Language Specification states:
Therefore, as long as there are no other static fields or static methods in the class, the Singleton instance will not be initialized until the method getInstance() is invoked the first time.
public class Singleton { private static class InstanceHolder { static final Singleton INSTANCE = new Singleton(); } public static Singleton getInstance() { return InstanceHolder.INSTANCE; } private Singleton() {} }
This initializes the INSTANCE variable on the first call to Singleton.getInstance(), taking advantage of the language's thread safety guarantees for static initialization without requiring additional synchronization
This type of Singleton is thread safe, and prevents unnecessary locking after the Singleton instance has been created.
Version ≥ Java SE 5 public class MySingleton { // instance of class private static volatile MySingleton instance = null; // Private constructor private MySingleton() { // Some code for constructing object } public static MySingleton getInstance() { MySingleton result = instance; //If the instance already exists, no locking is necessary if(result == null) { //The singleton instance doesn't exist, lock and check again synchronized(MySingleton.class) { result = instance; if(result == null) { instance = result = new MySingleton(); } } } return result; } }
It must be emphasized -- in versions prior to Java SE 5, the implementation above is incorrect and should be avoided. It is not possible to implement double-checked locking correctly in Java prior to Java 5.
Learn All in Tamil © Designed & Developed By Tutor Joes | Privacy Policy | Terms & Conditions