Skip to main content

Singleton in Java

Singleton using Enum in Java

This is the way we generally declare Enum Singleton , it may contain instance variable and instance method but for sake of simplicity I haven’t used any, just beware that if you are using any instance method than you need to ensure thread-safety of that method if at all it affect the state of object. By default creation of Enum instance is thread safe but any other method on Enum is programmers responsibility.

/**
* Singleton pattern example using Java Enum
*/
public enum EasySingleton{
    INSTANCE;
}

You can acess it by EasySingleton.INSTANCE, much easier than calling getInstance() method on Singleton.


Singleton using double checked locking

Below code is an example of double checked locking in Singleton pattern, here getInstance() method checks two times to see whether INSTANCE is null or not and that’s why it’s called double checked locking pattern

/**
* Singleton pattern example with Double checked Locking
*/
public class DoubleCheckedLockingSingleton{
     
private volatile DoubleCheckedLockingSingleton INSTANCE;

     
private DoubleCheckedLockingSingleton(){}

     
public static DoubleCheckedLockingSingleton getInstance(){
         
if(INSTANCE == null){
            
synchronized(DoubleCheckedLockingSingleton.class){
                
//double checking Singleton instance
                
if(INSTANCE == null){
                    INSTANCE 
= new DoubleCheckedLockingSingleton();
                
}
            
}
         
}
         
return INSTANCE;
     
}
}



Singleton pattern with static factory method

Since Singleton instance is static and final variable it initialized when class is first loaded into memory so creation of instance is inherently thread-safe.

/**
* Singleton pattern example with static factory method
*/


public class Singleton{
    //initailzed during class loading
    private static final Singleton INSTANCE = new Singleton();

    //to prevent creating another instance of Singleton
    private Singleton(){}

    public static Singleton getSingleton(){
        return INSTANCE;
    }
}

You can call Singleton.getSingleton() to get access of this class.


Enum Singletons handled Serialization by themselves

Another problem with conventional Singletons are that once you implement serializable interface they are no longer remain Singleton because readObject() method always return a new instance just like constructor in Java. You can avoid that by using readResolve() method and discarding newly created instance by replacing with Singleton as shown in below example :

    //readResolve to prevent another instance of Singleton
    
private Object readResolve(){
        
return INSTANCE;
    
}

This can become even more complex if your Singleton Class maintain state, as you need to make them transient, but with Enum Singleton, Serialization is guaranteed by JVM.

Comments

Popular posts from this blog

JUnit – Run unit test in an Sequence / Order

In JUnit, we can use @FixMethodOrder(MethodSorters.xxx) to run the test methods in a sequence or order.

import org.junit.FixMethodOrder;import org.junit.Test;import org.junit.runners.MethodSorters;importstatic org.hamcrest.CoreMatchers.is;importstatic org.junit.Assert.assertThat;//Sorts by method name@FixMethodOrder(MethodSorters.NAME_ASCENDING)publicclassExecutionOrderTest{@TestpublicvoidtestB(){assertThat(1+1,is(2));}@Testpublicvoidtest1(){assertThat(1+1,is(2));}@TestpublicvoidtestA

Create Runnable Jar - Eclipse Options

When exporting to a Runnable Jar, there are three options in eclipse Helios. Extract required libraries into JARPackage required libraries into JARCopy required libraries into sub folder next to JAR. What are differences : Extract required libraries into JAR - Extracts the actual .class files from the libraries your app uses and puts those .class files inside the runnable JAR. So, the runnable JAR will not only contain the .class files of your application, but also the .class files of all the libraries your application uses. Package required libraries into JAR - Puts the actual JAR files of the libraries into your runnable JAR. Normally, a JAR file within a JAR file cannot be loaded by the JVM. But Eclipse adds special classes to the runnable JAR to make this possible. Copy required libraries into sub folder next to JAR - Keeps the library JARs completely separate from the runnable JAR, so the runnable JAR will only contain the .class files of your application. Option #2 is convenient be…