简体   繁体   English

使用ConcurrentHashMap模拟锁,impl可以安全吗?

[英]Using ConcurrentHashMap to simulate the lock, is the impl OK safe?

I read some interesting code from an open source project, and I don't understand it really. 我从一个开放源代码项目中读取了一些有趣的代码,但我真的不太理解。

The concurrentMapExample below is a java.util.concurrent.ConcurrentMap. 下面的concurrentMapExample是一个java.util.concurrent.ConcurrentMap。 Can the code below prevent multiple threads return isLocked=true at the same time? 下面的代码可以防止多个线程同时返回isLocked = true吗?

public boolean tryLock()
{
    isLocked = concurrentMapExample.putIfAbsent(key, "") == null;
    return isLocked;
}

Can the code below prevent multiple threads return isLocked=true at the same time? 下面的代码可以防止多个线程同时返回isLocked = true吗?

Yes. 是。 This code is thread-safe and only one thread will return null. 此代码是线程安全的,只有一个线程将返回null。 Other threads calling putIfAbsent(...) afterwards with the same key (!!) will get the "" value and isLocked will be false. 随后使用相同的key (!!)调用putIfAbsent(...)其他线程将获得""值,而isLocked将为false。

To be pedantic, I would suggest that you wrap the equality check in a parens or maybe do something like the following to improve readability: 出于学究的考虑,我建议您将等式检查包装在括号中,或者可能执行以下类似操作以提高可读性:

if (concurrentMapExample.putIfAbsent(key, "") == null)
   return true;
else
   return false;

This seems like an academic question but for posterity, there obviously are better wants to do this. 这似乎是一个学术问题,但对于后代,显然最好是这样做。 For example, the same logic using an AtomicBoolean would be: 例如,使用AtomicBoolean的相同逻辑将是:

private final AtomicBoolean isLocked = new AtomicBoolean(false);
...
return isLocked.compareAndSet(false, true);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM