栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 前沿技术 > 大数据 > 大数据系统

zookeeper源码解析(九)

zookeeper源码解析(九)

2021SC@SDUSC

前言

本节介绍PathTrie类的静态内部类TrieNode,即字典树的节点类

TrieNode

成员变量

         //节点存储的值
         final String value;
         //Map,存储子节点的value到子节点的映射
         final Map children;
         //property为true,当且仅当对应的路径(从根节点到该节点)存在
         boolean property;
         //节点的父节点
         TrieNode parent;

构造函数:

         //private构造函数,只对当前外部类开放
         private TrieNode(TrieNode parent, String value) {
             this.value = value;
             this.parent = parent;
             this.property = false;
             //初始化容量为4,平衡内存消耗与哈希表的更新效率
             this.children = new HashMap<>(4);
         }

parent,property的get/set方法,value的get方法:

         TrieNode getParent() {
             return this.parent;
         }

         
         void setParent(TrieNode parent) {
             this.parent = parent;
         }

         
         void setProperty(boolean prop) {
             this.property = prop;
         }

        
         boolean hasProperty() {
             return this.property;
         }

         
         public String getValue() {
             return this.value;
         }

addChild,deleteChild方法:

         //事实上在zookeeper中调addChild前总会先判断hashmap中是否已有对应的key
         //但该函数的实现依然是用了putIfAbsent来保证健壮性
         void addChild(String childName, TrieNode node) {
             this.children.putIfAbsent(childName, node);
         }

         
         
         void deleteChild(String childName) {
             this.children.computeIfPresent(childName, (key, childNode) -> {
                 //删除一个子节点,首先子节点一定是propety设为false
                 childNode.setProperty(false);
                 
                 //而子节点对象是否要删除,要取决于该子节点是否是叶子节点
                 //如果该子节点没有子节点,那么就可以直接在hashmap中删除它了
                 if (childNode.isLeafNode()) {
                     childNode.setParent(null);
                     return null;
                 }

                 return childNode;
             });
         }

getChild,getChildren方法:

         //根据子节点存的值,来获取该节点的子节点
         TrieNode getChild(String childName) {
             return this.children.get(childName);
         }

         
         //获取该节点的子节点们存储的值集合
         Collection getChildren() {
             return children.keySet();
         }

isLeafNode方法:

         //判断该节点是否是叶子节点,通过children是否为空(即该节点是否有子节点)
         boolean isLeafNode() {
             return children.isEmpty();
         }

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/629237.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号