簡體   English   中英

Java中的同步嵌套集合

[英]Synchronized nested collections in java

我試圖按照以下方式在Java中創建線程安全的數據結構:

public class A {

    ConcurrentHashMap<String, Set<String>> subscriptions

    private void addSubscription(String server, String client) {
        Set<String> clients = subscriptions.get(server);
        if (clients == null) {
            clients = Collections.newSetFromMap(new ConcurrentHashMap<String, Boolean>());
            subscriptions.put(server, agents);
        }
        clients.add(client);
    }

    private synchronized void removeSubscription(String server, String client) {
        Set<String> clients = subscriptions.get(server);
        if (clients != null) {
            clients.remove(client);
            if (clients.isEmpty()) {
                subscriptions.remove(server, agents);
            }
        }
    }
}

但是,看來我需要添加其他同步(我猜是為了保護對Set的訪問)。 是否在這里可以使用更好的集合,還是只需要為此添加適當的同步?

是什么讓您認為您需要其他同步? 我不知道為什么會這樣。 我要更改的一件事是addSubscription應該檢查給定服務器的設置是否不存在,並自動添加它。 這樣,當兩個線程將客戶端添加到同一服務器時,可以避免爭用情況:

Set<String> newClients = Collections.newSetFromMap(new ConcurrentHashMap<String, Boolean>());
Set<String> clients = subscriptions.putIfAbsent(server, newClients);
if(clients == null) clients = newClients;
clients.add(client);

另外,在設置為空后,我不會從地圖中刪除該設置。 否則,會出現另一種競爭狀況:在您檢查了大小並發現它為空之后,可能有人添加了一個新客戶端,然后您將其丟棄。 只是讓空集呆在那里,那沒有什么害處。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM