栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

ConcurrentHashMap随笔

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

ConcurrentHashMap随笔

线程安全集合类概述

线程安全集合类可以分为三大类:

遗留的线程安全集合如Hashtable,Vector

使用Collections装饰的线程安全集合,如:

Collections.synchronizedCollectionCollections.synchronizedListCollections.synchronizedMapCollections.synchronizedSetCollections.synchronizedNavigableMapCollections.synchronizedNavigableSetCollections.synchronizedSortedMapCollections.synchronizedSortedSet

java.util.concurrent.*

重点介绍java.util.concurrent.*下的线程安全集合类,可以发现它们有规律,里面包含三类关键词:Blocking 、CopyOnWrite、Concurrent

Blocking 大部分实现基于锁,并提供用来阻塞的方法

CopyOnWrite之类容器修改开销相对较重

Concurrent类型的容器

内部很多操作使用cas优化,一般可以提供较高吞吐量

弱一致性

遍历时弱一致性,例如,当利用迭代器遍历时,如果容器发生修改,迭代器仍然可以进行遍历,这时内容是旧的求大小弱一致性,size操作未必是100%读取弱一致性

遍历时如果发生了修改,对于非线程安全来讲,使用fail-fast机制也就是让遍历立刻失败,抛出ConcurrentModificationException,不再继续遍历

重要属性和内部类

     private transient volatile int sizeCtl;

     // 整个 ConcurrentHashMap 就是一个Node[]
     static class Node implements Map.Entry {}


      //  hash 表
     transient volatile Node [] table;

     // 扩容时的 新 hash 表
    private transient volatile Node [] nextTable;


    // 扩容时如果某个 bin 迁移完毕, 用ForwardingNode 作为旧 table bin 的头结点
    static final class ForwardingNode extends Node {}

    // 用在 compute 以及 computeIfAbsent时,用来占位,计算完成后替换为普通 Node
    static final class ReservationNode extends Node {}

    // 作为treebin 的头结点,存储root 和 first
    static  final class TreeBin extends  Node {}

    // 作为 treebin 的节点,存储parent,left,right
    static final class TreeNode extends Node {}

重要方法

      // 获取 Node[] 中第 i 个Node
    static final  Node tabAt(Node[] tab,int i);

      // cas 修改 Node[] 中第 i 个Node 的值,c 为旧值 ,v 为新值
    static final  boolean casTabAt(Node [] tab,int i,Node c,Node v);

    // 直接修改Node[] 中第 i个 Node 的值,v为新值
    static final  void setTabAt(Node [] tab ,int i,Node v)

ConcurrentHashMap原理具体分析

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

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

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