问题
public class ConnectionManager {
private static Map <String, ConnectionManager> managerInstances = new HashMap<String, ConnectionManager>();
private String dsKey;
private ConnectionManager(String dsKey){
this.dsKey = dsKey;
}
public static ConnectionManager getInstance(String dsKey){
ConnectionManager managerInstance = managerInstances.get(dsKey);
if (managerInstance == null) {
synchronized (ConnectionManager.class) {
managerInstance = managerInstances.get(dsKey);
if (managerInstance == null) {
managerInstance = new ConnectionManager(dsKey);
managerInstances.put(dsKey, managerInstance);
}
}
}
return managerInstance;
}
}
I recently saw this code somewhere where the Singleton pattern was not used as per book definition from GoF. Singleton is storing a Map
of its own instances.
What kind of singleton can this be called? Or is this a valid use of Singleton?
回答1:
It's not a singleton. It's called multiton pattern.
Rather than have a single instance per application, the multiton pattern instead ensures a single instance per key.
回答2:
That multiton seems broken as it uses a double-checked locking idiom which is not thread safe in Java. In particular, when calling getInstance(s)
, with s
a non-null String, you could receive a non-null reference pointing to a ConnectionManager
whose dsKey
is null.
It would be much better to use a thread safe ConcurrentHashMap instead and remove the need for synchronization.
来源:https://stackoverflow.com/questions/18119217/which-kind-of-singleton-is-this