0

Consider the following code:

public void iterateItems() {
    //list contains several keys
    list.parallelStream().forEach(key-> compute(key));
}

private void compute(final String key) {
    final String argA = "A";
    final String argB = "B";
    MyClass.getInstance(key, argA, argB);
}

public class MyClass {
    private final static Map<String, MyClass> cache = new ConcurrentHashMap<>();

    private MyClass(final String argA, final String argB) {
        ...
    }

    public static MyClass getInstance(final String key, final String argA, final String argB) {
        return cache.computeIfAbsent(key, (k) -> new MyClass(argA, argB));
    }
}

My understanding is the cache is initialized by the ClassLoader before any static method can be called. However, I am wondering if one thread can access cache in the middle of instantiation in the other thread. Will this result in NullPointerException? Is this thread-safe? What do I need to do to make it thread-safe?

  • What is the issue you are facing currently? – Arvind Kumar Avinash Aug 03 '20 at 16:49
  • Apart from the fact that you can't instantiate `ConcurrentMap` because it's an interface, this code seems fine and I see no potential race conditions in it. The `cache` field is definitely initialiized before `getInstance()` can first be called and `computeIfAbsent` for a `ConcurrentHashMap` is thread-safe. – Joachim Sauer Aug 03 '20 at 16:50
  • It should have been ConcurrentHashMap. There is no issue but I was just reviewing some code and wanted to know if it was possible if Thread A calls getInstance(), the cache will be initialized. When threadB calls getInstance is it guaranteed that the cache is initialized by the time the getInstance call is made in thread B. – Albert Johnson Aug 03 '20 at 16:53

0 Answers0