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+.