开发者社区 > 云原生 > 正文

NodeSelectorSlot类中,向map中加入新的DefaultNode时,为什么不是直接通过

Type: feature request Thank you for your attention,I have a question to ask. the code is following: private volatile Map<String, DefaultNode> map = new HashMap<String, DefaultNode>(10); public void entry(Context context, ResourceWrapper resourceWrapper, Object obj, int count, boolean prioritized, Object... args) throws Throwable { DefaultNode node = map.get(context.getName()); if (node == null) { synchronized (this) { node = map.get(context.getName()); if (node == null) { node = new DefaultNode(resourceWrapper, null); HashMap<String, DefaultNode> cacheMap = new HashMap<String, DefaultNode>(map.size()); cacheMap.putAll(map); cacheMap.put(context.getName(), node); map = cacheMap; } // Build invocation tree ((DefaultNode)context.getLastNode()).addChild(node); } } context.setCurNode(node); fireEntry(context, resourceWrapper, node, count, prioritized, args); } When node == null, we will new a {@link DefaultNode} and add to map.Your mathod is building an object named cacheMap first,and than assigning it to map.Why not put the node to map directly as follow: map.put(context.getName(), node);,What are the considerations?

当 node == null 的时候,我们通过新建一个DefaultNode加入到map中,代码中的方法是先定义一个cacheMap对象,然后将map原有的值以及新建的node加入到cacheMap中。为什么不直接通过map.put(context.getName(), node);将node加入到map呢,是出于什么考虑才这样做的?

原提问者GitHub用户xgxizz

展开
收起
学习娃 2023-05-19 15:58:22 57 0
1 条回答
写回答
取消 提交回答
  • 为了线程安全,使用了 copy on write

    原回答者GitHub用户liqiangz

    2023-05-19 20:48:24
    赞同 展开评论 打赏
问答标签:
问答地址:

阿里云拥有国内全面的云原生产品技术以及大规模的云原生应用实践,通过全面容器化、核心技术互联网化、应用 Serverless 化三大范式,助力制造业企业高效上云,实现系统稳定、应用敏捷智能。拥抱云原生,让创新无处不在。

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载