-2
\$\begingroup\$

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.

\$\endgroup\$
2
  • 1
    \$\begingroup\$ I think this covers it pretty well already: codereview.stackexchange.com/questions/27296/… \$\endgroup\$
    – Tunaki
    Commented Feb 17, 2016 at 19:23
  • \$\begingroup\$ Please include your MYDB class as well — at least the MYDB.getDataSource() function. \$\endgroup\$ Commented Feb 17, 2016 at 20:40

1 Answer 1

1
\$\begingroup\$

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;
    }
}
\$\endgroup\$
1
  • 1
    \$\begingroup\$ 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. \$\endgroup\$
    – slartidan
    Commented Mar 3, 2016 at 16:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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