// 采用Immutability模式,每次上线、下线都创建新的Router对象或删除对应的Router对象 @Data @AllArgsConstructor public class Router { private final String ip; private final Integer port; private final String iFace; @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Router router = (Router) o; return Objects.equals(ip, router.ip) && Objects.equals(port, router.port) && Objects.equals(iFace, router.iFace); } @Override public int hashCode() { return Objects.hash(ip, port, iFace); } } class RouterTable { // <接口名 , 路由集合> private ConcurrentHashMap<String, CopyOnWriteArraySet<Router>> routingTable = new ConcurrentHashMap<>(); // 获取路由 public Set<Router> get(String iFace) { return routingTable.get(iFace); } // 增加路由 public void add(Router router) { CopyOnWriteArraySet<Router> set = routingTable.computeIfAbsent(router.getIFace(), iFace -> new CopyOnWriteArraySet<>()); set.add(router); } // 删除路由 public void remove(Router router) { CopyOnWriteArraySet<Router> set = routingTable.get(router.getIFace()); if (set != null) { set.remove(router); } } }
转载请注明出处:http://zhongmingmao.me/2019/05/19/java-concurrent-copy-on-write/
访问原文「 Java并发 -- Copy-on-Write模式 」获取最佳阅读体验并参与讨论