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.
4 Answers 4
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
.
-
valueOf()
is a good name that is consistent with core Java as well as many frameworks.user22815– user228152014年11月25日 15:43:07 +00:00Commented Nov 25, 2014 at 15:43
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.
-
This is really funny as we just joked that the pattern should be called a Multiton and dismissed it because of the contradiction of "singleton" and "multiple". At least I can now solve the parallel instantiation with clear conscience as it is not solved in the pattern, I wonder if that is because it is not needed in most cases and because it will make the code to complicated or if there are other reasons behind it.Konrad Höffner– Konrad Höffner2014年11月25日 13:48:46 +00:00Commented Nov 25, 2014 at 13:48
-
P.S.: Keeping the question state unanswered for a while in case some one has an implementation of a parallel variant.Konrad Höffner– Konrad Höffner2014年11月25日 14:15:08 +00:00Commented Nov 25, 2014 at 14:15
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;
}
}
valueOf()
methods that every primitive wrapper in Java has, as well as a few other classes such asBigDecimal
. Not the JavaDoc, but the actual source code that ships with the JDK.null
keys?