使用 ConcurrentMap 进行双重检查锁定ConcurrentMap

2023-09-07 16:15:51 作者:性感不是骚.

我有一段代码可以由多个线程执行,它需要执行 I/O 绑定操作以初始化存储在 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); // I/O-bound, expensive operation
        map.put(key, resource);
    }

使用上面的代码,多个线程可能会检查 ConcurrentMap 并看到资源不存在,并且都尝试调用昂贵的 getResource().为了确保只对共享资源进行一次初始化并在资源初始化后使代码高效,我想做这样的事情:

With the above code, multiple threads may check the ConcurrentMap and see that the resource isn't there, and all attempt to call getResource() which is expensive. In order to ensure only a single initialization of the shared resource and to make the code efficient once the resource has been initialized, I want to do something like this:

    String key = "somekey";
    Resource resource;
    if (!map.containsKey(key)) {
        synchronized (map) {
            if (!map.containsKey(key)) {
                resource = getResource(key);
                map.put(key, resource);
            }
        }
    }

这是双重检查锁定的安全版本吗?在我看来,由于检查是在 ConcurrentMap 上调用的,因此它的行为类似于声明为 volatile 的共享资源,因此可以防止任何部分初始化"问题这可能会发生.

Is this a safe version of double checked locking? It seems to me that since the checks are called on ConcurrentMap, it behaves like a shared resource that is declared to be volatile and thus prevents any of the "partial initialization" problems that may happen.

推荐答案

是的,它很安全.

如果 map.containsKey(key) 为真,根据 doc,map.put(key, resource) 发生在它之前.因此 getResource(key) 发生在 resource = map.get(key) 之前,一切正常.

If map.containsKey(key) is true, according to doc, map.put(key, resource) happens before it. Therefore getResource(key) happens before resource = map.get(key), everything is safe and sound.