I read a lot on stackoverflow regarding the creation of singleton classes using enum. I must have missed something because i can't reach the INSTANCE anywhere.
this is my code:
public class UserActivity { private DataSource _dataSource; private JdbcTemplate _jdbcTemplate; static enum Singleton { INSTANCE; private static final UserActivity singleton = new UserActivity(); public UserActivity getSingleton() { return singleton; } } public UserActivity() { this._dataSource = MysqlDb.getInstance().getDataSource(); this._jdbcTemplate = new JdbcTemplate(this._dataSource); } public void dostuff() { ... } }
and outside I'm trying to do
UserActivity.INSTANCE.getSingleton()
or
UserActivity.Singleton.
but eclipse's code completion doesn't find anything
thanks!
Enum Singletons are new ways of using Enum with only one instance to implement the Singleton pattern in Java. While there has been a Singleton pattern in Java for a long time, Enum Singletons are a comparatively recent term and in use since the implementation of Enum as a keyword and function from Java 5 onwards.
The singleton pattern restricts the instantiation of a class to one object. INSTANCE is a public static final field that represents the enum instance. We can get the instance of the class with the EnumSingleton. INSTANCE but it is better to encapsulate it in a getter in case if we want to change the implementation.
In your case, the singleton will be initialised when the enum class is loaded, i.e. the first time enumClazz is referenced in your code. So it is effectively lazy, unless of course you have a statement somewhere else in your code that uses the enum.
This technique is absolutely thread-safe. An enum value is guaranteed to only be initialized once, ever, by a single thread, before it is used.
The trick is to make the enum itself the singleton. Try this:
public enum UserActivity { INSTANCE; private DataSource _dataSource; private JdbcTemplate _jdbcTemplate; private UserActivity() { this._dataSource = MysqlDb.getInstance().getDataSource(); this._jdbcTemplate = new JdbcTemplate(this._dataSource); } public void dostuff() { ... } } // use it as ... UserActivity.INSTANCE.doStuff();
INSTANCE
is a member of Singleton
, not of UserActivity
- so you'd need:
UserActivity.Singleton.INSTANCE.getSingleton();
However, you haven't actually made UserActivity
a singleton - normally you'd make the type itself an enum, not embed an enum within the type...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With