亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

并發哈希圖刪除復雜值

并發哈希圖刪除復雜值

拉風的咖菲貓 2023-12-13 14:31:31
我有哈希映射:private final ConcurrentHashMap<String, List<Client>> clients;和班級:public static class Client {    private String name; // it is also the key of the map    private String url;}我從多個線程中調用線程安全方法“ removeElement ”,該方法必須從列表中刪除一個值。@Overridepublic CompletableFuture<Void> removeClient(Client client) {    return CompletableFuture.runAsync(() ->            clients.entrySet().removeIf(v ->                    v.getValue().removeIf(                            it -> client.url.equals(it.url))            )    );}但當然,這是行不通的。當我得到 Method throws 'java.lang.UnsupportedOperationException' 異常時,我解決了這樣的問題:@Overridepublic CompletableFuture<Void> removeClient(Client client) {    return CompletableFuture.runAsync(() -> {                List<Client> currentClients = new ArrayList<>(clients.get(client.getName()));                currentClients.remove(client);                if (currentClients.isEmpty()) {                    clients.remove(client.getName());                } else {                    clients.put(client.getName(), currentClients);                }            }    );}但它不是線程安全的。我怎樣才能在這里實現它?也許有更優雅的方法來解決它?
查看完整描述

1 回答

?
Cats萌萌

TA貢獻1805條經驗 獲得超9個贊

我認為您可以ConcurrentHashMap::computeIfPresent在這種情況下使用假設相同的List實例沒有放置相同的鍵:

CompletableFuture.runAsync(() -> {

? ? clients.computeIfPresent(client.getName(), (name, clients1) -> {

? ? ? ? List<Client> currentClients = new ArrayList<>(clients1);

? ? ? ? currentClients.remove(client);

? ? ? ? return currentClients.isEmpty() ? null : currentClients;

? ? });

});

由于computeIfPresent是原子執行的,并且我們在 remappingFunction 中使用列表的副本 - 它應該可以工作。


正如我們在文檔中可以讀到的:


如果指定鍵的值存在,則嘗試計算給定鍵及其當前映射值的新映射。整個方法調用都是原子執行的。當計算正在進行時,其他線程對此映射的某些嘗試更新操作可能會被阻止,因此計算應該簡短且簡單,并且不得嘗試更新此映射的任何其他映射。


查看完整回答
反對 回復 2023-12-13
  • 1 回答
  • 0 關注
  • 144 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號