配置存储不仅维护了一个树结构,还实现了临时节点的功能,临时节点的生命周期和客户端会话绑定在一起,客户端会话失效,则这个节点就会被自动清除。
DataTree内部维护了一个hastable结构,key为sessionid,value为该session创建的临时节点。客户端会话失效,其创建的临时节点都会被删除。
private final Map<Long, HashSet<String>> ephemerals = new ConcurrentHashMap<Long, HashSet<String>>(); public HashSet<String> getEphemerals(long sessionId) { HashSet<String> retv = ephemerals.get(sessionId); ... HashSet<String> cloned = null; synchronized (retv) { cloned = (HashSet<String>) retv.clone(); } return cloned; } public String createNode(String path, byte data[], List<ACL> acl, long ephemeralOwner, long zxid, long time) throws KeeperException.NoNodeException, KeeperException.NodeExistsException { ... if (ephemeralOwner != 0) { HashSet<String> list = ephemerals.get(ephemeralOwner); if (list == null) { list = new HashSet<String>(); ephemerals.put(ephemeralOwner, list); } synchronized (list) { list.add(path); } } } ... } public void deleteNode(String path, long zxid) throws KeeperException.NoNodeException { ... DataNode node = nodes.get(path); ... long eowner = node.stat.getEphemeralOwner(); if (eowner != 0) { HashSet<String> nodes = ephemerals.get(eowner); if (nodes != null) { synchronized (nodes) { nodes.remove(path); } } } ... } void killSession(long session, long zxid) { ... HashSet<String> list = ephemerals.remove(session); if (list != null) { for (String path : list) { ... deleteNode(path, zxid); ... } } }