This is a sample of the basic pattern I’ve been using for a Factory that returns a thread-safe Singleton:
public class UserServiceFactory {
private volatile static UserService userService;
private UserServiceFactory() { }
public static UserService getInstance() {
if (userService == null) {
synchronized(UserServiceImpl.class) {
if (userService == null) {
userService = new UserServiceImpl();
}
}
}
return userService;
}
}
It uses both volatile and the double check idiom to ensure that a single instance is created and is visible across threads.
Is there a less verbose and/or less expensive way to accomplish the same goal in 1.6+.
Use the Initialization On Demand Holder idiom, it’s simpler and better readable:
However, I’d prefer Just Create One idiom.
Update: as your question history confirms, you’re using Java EE. If your container supports it, you could also make it a
@SingletonEJB and use@EJBto inject it (although@Statelessis preferable since@Singletonis by default read-locked).with e.g. in a JSF managed bean
This way you delegate the instantiation job to the container.