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?