存在的關鍵在Java的ConcurrentMap
,有remove(key, expectedValue)
,這將返回之一:獲得無論從ConcurrentMap.remove()
- 預期值在那裏,已被刪除。
- 期望值不存在,所以沒有被刪除。
但我希望得到的是一個:
- 預期值在那裏,已被刪除。
- 該鍵下有一個值,但不是預期的值,所以它沒有被刪除。
- 該密鑰下沒有任何值,所以它沒有被刪除。
如何以併發和線程安全的方式獲取此信息?
這是代碼我想safify
// 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)'而不是'會話。刪除(會話,現有)'? – dogbane 2012-01-04 10:41:10
你能描述一下你如何使用這張地圖的整體情況嗎? – axtavt 2012-01-04 11:02:07
@dogbane Woops :) – 2012-01-04 16:28:07