I frequently have this problem but didn’t find it as an established programming pattern. I have some Class C whose equality is determined by some key k and I want to prevent time-consuming initialisation of additional equal objects.
This is my implementation but the synchronized get method prevents parallel instantiation.
Class C
{
Key key;
private static Map<Key,C> cs = new HashMap<Key,C>();
private C(Key key)
{
// this takes a long time
}
synchronized static C get(Key key)
{
C c = cs.get(key);
if(c==null)
{
c = new C(key);
cs.put(key,c);
}
return c;
}
@Override public boolean equals(Object o)
{
if (this == o) return true;
if (o == null) return false;
if (getClass() != o.getClass()) return false;
C other = (C) o;
if (key == null)
{
if (other.key != null) return false;
}
else if (!key.equals(other.key)) return false;
return true;
}
@Override public int hashCode() {..}
}
Can you point me to an existing best-practise to this, if it exists, or show me how to implement this optimally? My criteria are clarity, brevity, performance and thread-safeness.
7
In his book Effective Java, Josuha Bloch mentions this pattern as a good practice for this sort of scenario (Item 1: Consider static factory methods instead of constructors).
Some common alternative names for the method that here is called C.get
are the following C.getInstance
, C.valueOf
, C.of
.
1
This is a variation of the singleton pattern, called Multiton.
You will have to manage the global state introduced with the HashMap
. This can lead to diffucult unit testing.
The implementation of the synchronized
method looks the same, as shown in the Wikipedia article. But if you can restructure your use case, so that you can avoid the synchronizing of objects it would be preferable.
2
If the only problem with initializing multiple copies of a single object value is the time/memory it takes, you may want to consider switching to a ConcurrentHashMap
and using the computeIfAbsent
method to initialize values. This has the side effect that two copies of a single value may be initialized, however only one will be retained (the second will be garbage collected at some point) and all threads will be able to precede simultaneously.
This solution is not applicable, however, if initialization has side effects.
If the Key object is already unique itself, not by equals()
but by instance, and in case the key would actually never be null
(and the code could be changed / the null
key case could be removed), you could change the get()
function to:
static C get(Key key) {
synchronized (key) {
C c = cs.get(key);
if (c==null) {
c = new C(key);
cs.put(key,c);
}
return c;
}
}