Code Review Stack Exchange is a question and answer site for peer programmer code reviews. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I just wanted to implement the enum singleton in java. Here is my implementation where I have tried to create a singleton DataSource instance:

public enum EasySingleton {
    INSTANCE;

    private DataSource dataSource;

    private EasySingleton() {
        this.dataSource = MYDB.getDataSource();

    }

    public DataSource getDataSource(){
        return dataSource;
    }

}

and get this DataSource instance just like this:

DataSource dataSource = EasySingleton.INSTANCE.getDataSource();

I just wanted to confirm whether my implementation is correct or not. If it is wrong then please tell me how to implement the enum singleton to create a singleton DataSource instance.

share|improve this question
1  
I think this covers it pretty well already: codereview.stackexchange.com/questions/27296/… – Tunaki Feb 17 at 19:23
    
Please include your MYDB class as well — at least the MYDB.getDataSource() function. – 200_success Feb 17 at 20:40

This is not a good use for a enum singleton. What you have there is a wrapper for MYDB.getDataSource(). You could handle that with a static synchronized method.

public class DataSourceAdapter {
    private static DataSource dataSource;
    public static synchronized DataSource getDataSource(){
        if(dataSource == null){
            dataSource = MYDB.getDataSource();
        }
        return dataSource;
    }
}
share|improve this answer
1  
The difference between yours and @Rahul s solution is the execution time. I would prefer your solution:if anything goes wrong the stacktrace will include the reason of the instanciation. And application startup will be faster. – slartidan Mar 3 at 16:52

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.