I have a singleton factory (edit: renamed "loader" to avoid confusion with factory pattern) that creates objects (in my example DAOs) or returns them if already created:
public class DAOLoader {
private static final DAOLoader INSTANCE = new DAOLoader();
private UserDAO userDAO;
private MessageDAO messageDAO;
private final Object lockUserDAO = new Object();
private final Object lockMessageDAO = new Object();
private DAOLoader() {}
public static DAOLoader getInstance() {
return INSTANCE;
}
public UserDAO getUserDAO() {
if (userDAO == null) {
synchronized(lockUserDAO) {
if (userDAO == null) userDAO = new UserDAO();
}
}
return userDAO;
}
public MessageDAO getMessageDAO() {
if (messageDAO == null) {
synchronized(lockMessageDAO) {
if (messageDAO == null) messageDAO = new MessageDAO();
}
}
return messageDAO;
}
}
First, do you guys see anything wrong with this code?
In this example, is a different lock for each method required or should I just use 1 global lock? Would a deadlock happen with a unique global lock? If not, the only drawback would be that if the lock is used by some thread to create a DAO and another thread would like to create another DAO, it would have to wait for the lock to be released?
Thanks.
static
. – Chewvolatile
to my DAO members. – Chew