Double checked locking with ConcurrentMap
问题 I have a piece of code that can be executed by multiple threads that needs to perform an I/O-bound operation in order to initialize a shared resource that is stored in a ConcurrentMap . I need to make this code thread safe and avoid unnecessary calls to initialize the shared resource. Here's the buggy code: private ConcurrentMap<String, Resource> map; // ..... String key = "somekey"; Resource resource; if (map.containsKey(key)) { resource = map.get(key); } else { resource = getResource(key);