0

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
  • Keep in mind that synchronization has a performance cost in the single-threaded case. You should provide both a synchronized and non-synchronized get. You should also ask yourself if this is really necessary. Garbage collectors are good at dealing with short-lived objects. Are you really creating such a large number of these things that it's a problem?
    – Doval
    Commented Nov 25, 2014 at 13:23
  • @Doval: I only create several hundreds of them so the synchronization overhead itself isn't problematic but the non-paralellism is because of my time consuming object creation. Commented Nov 25, 2014 at 13:41
  • 1
    I recommend taking a look at the static valueOf() methods that every primitive wrapper in Java has, as well as a few other classes such as BigDecimal. Not the JavaDoc, but the actual source code that ships with the JDK.
    – user22815
    Commented Nov 25, 2014 at 15:44
  • Can you give an example of a situation where you've needed to do this? It seems extremely situational Commented Nov 25, 2014 at 17:25
  • 2
    Do you really have to allow null keys? Commented Nov 25, 2014 at 20:00

4 Answers 4

1

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.getare the following C.getInstance, C.valueOf, C.of.

1
  • valueOf() is a good name that is consistent with core Java as well as many frameworks.
    – user22815
    Commented Nov 25, 2014 at 15:43
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
  • 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. Commented 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. Commented Nov 25, 2014 at 14:15
1

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.

0

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;
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.