我有哈希映射:
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 ”,该方法必须从列表中删除一个值。
@Override
public 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' 异常时,我解决了这样的问题:
@Override
public 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);
}
}
);
}
但它不是线程安全的。我怎样才能在这里实现它?也许有更优雅的方法来解决它?
Cats萌萌
相关分类