【发布时间】:2012-01-04 10:26:31
【问题描述】:
在 Java 的 ConcurrentMap 中,有 remove(key, expectedValue),它返回以下之一:
- 预期值存在但已被删除。
- 预期值不存在,因此尚未删除。
但我想得到的是以下之一:
- 预期值存在但已被删除。
- 该键下有一个值,但不是预期的值,因此尚未删除。
- 该键下没有值,因此尚未删除。
如何以并发和线程安全的方式获取这些信息?
这是我要验证的代码
// attempt to remove the old session...
if (!sessions.remove(player.getId(), existing)) {
// it was not removed...
if (sessions.containsKey(player.getId())) { // TODO threadsafe
// ...because in the meantime some other thread logged in as that user
throw new ServiceError(LobbyService.ERR_LOGIN_INVALID, Maps.create("reason", "already-logged-in"));
} else {
// ...because it was no longer there, which is as it should be
}
} else {
// it was removed, which is bad, because it shouldn't have been there still
log.warn("Kicking old session of " + player.getId() + " failed");
}
或概括:
if (!sessions.remove(key, expected)) {
if (sessions.containsKey(key)) { // TODO threadsafe
// 2
} else {
// 3
}
} else {
// 1
}
【问题讨论】:
-
不应该是
sessions.remove(player.getId(), existing)而不是sessions.remove(sessions, existing)吗? -
您能描述一下您如何使用该地图的总体情况吗?
标签: java concurrency thread-safety concurrenthashmap