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:
public class UserServiceFactory {
private UserServiceFactory () {}
private static class UserServiceHolder {
private static final UserService INSTANCE = new UserService();
}
public static UserService getInstance() {
return UserServiceHolder.INSTANCE;
}
}
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 @Singleton
EJB and use @EJB
to inject it (although @Stateless
is preferable since @Singleton
is by default read-locked).
@Singleton
public class UserService {}
with e.g. in a JSF managed bean
@EJB
private UserService userService;
This way you delegate the instantiation job to the container.