[英]Stealing a reference from ConcurrentHashMap before removing it. Correctness
ConcurrentHashMap
不會有條件地刪除元素並獲取它。 所以,我自己實現它:
private final ConcurrentHashMap<UUID, MyClass> map = new ConcurrentHashMap<>();
public MyClass removeIfAndGet(UUID key){
final MyClass[] arr = new MyClass[1];
return map.computeIfPresent(key, (x, v) -> {
if(v.isDone()){ // MyClass::isDone is thread-safe
arr[0] = v; // let's capture (steal) it!
return null; // let's remove it from a map!
}
return v; // v does not satisfy our requirement, don't remove that.
});
}
可以嗎? 我有一些疑問,因為在刪除引用之前不太好“竊取”引用。 它是否安全和正確(在多線程方面也是如此?)。 是的,我知道MyClass
本身必須是線程安全的。
PS我可以做得更好嗎?
為什么不通過覆蓋computeIfPresent()
方法來創建自己的ConcurrentHashMap
實現並讓它檢索當前映射(如果有)。 然后,調用 super 實現(它調用父級的 computeIfPresent 方法),如果它返回 null,則返回您檢索到的映射。
您可以查看computeIfPresent 是如何實現的,並在您自己的computeIfPresent 方法中執行類似的操作,但返回您想要的內容。 它仍然可以是線程安全的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.