-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\$
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
    \$\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 Mar 3 '16 at 16:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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