Java并发编程之并发容器ConcurrentHashMap(JDK1.8)解析

这个版本ConcurrentHashMap难度提升了很多,就简单的谈一下常用的方法就好了,可能有些讲的不太清楚,麻烦发现的大佬指正一下

主要数据结构

1.8将Segment取消了,保留了table数组的形式,但是不在以HashEntry纯链表的形式储存数据了,采用了链表+红黑树的形式储存数据;在使用get()方法时,使用纯链表的时间复杂度时O(n),而在使用红黑树的数据结构时,时间复杂度为O(logn),在查询的速度上有很大的提升;但是在创建的时候并非直接使用红黑树储存数据,而是依旧采用链表存储,但是但链表的长度超过8的时候就会转换成红黑树数据结构。

Node

依旧还是跟HashEntry的数据结构一致,采用链表的数据结构存储

static class Node<K,V> implements Map.Entry<K,V> {final int hash;final K key;volatile V val;volatile Node<K,V> next;Node(int hash, K key, V val, Node<K,V> next) {this.hash = hash;this.key = key;this.val = val;this.next = next;}//.....}

TreeNode

红黑树的数据结构原型,继承了Node

     /*** Nodes for use in TreeBins*/static final class TreeNode<K,V> extends Node<K,V> {TreeNode<K,V> parent;  // red-black tree linksTreeNode<K,V> left;TreeNode<K,V> right;TreeNode<K,V> prev;    // needed to unlink next upon deletionboolean red;TreeNode(int hash, K key, V val, Node<K,V> next,TreeNode<K,V> parent) {super(hash, key, val, next);this.parent = parent;}Node<K,V> find(int h, Object k) {return findTreeNode(h, k, null);}//......}

TreeBin

table数组中储存的就是TreeBin对象,存储了TreeNode<K,V>的根节点

     static final class TreeBin<K,V> extends Node<K,V> {TreeNode<K,V> root;volatile TreeNode<K,V> first;volatile Thread waiter;volatile int lockState;// values for lockStatestatic final int WRITER = 1; // set while holding write lockstatic final int WAITER = 2; // set when waiting for write lockstatic final int READER = 4; // increment value for setting read lock//...}

构造方法

在构造方法中,并没有做什么操作,仅仅是设置了一个属性值sizeCtl(也是容器的控制器)

sizeCtl:

负数:表示进行初始化或者扩容,-1表示正在初始化,-N,表示有N-1个线程正在进行扩容。

正数:0 表示还没有被初始化,>0的数,初始化或者是下一次进行扩容的阈值。

而实际的初始化是在put()方法中加载table数组

       /*** The array of bins. Lazily initialized upon first insertion.* Size is always a power of two. Accessed directly by iterators.*/transient volatile Node<K,V>[] table;/*** Table initialization and resizing control.  When negative, the* table is being initialized or resized: -1 for initialization,* else -(1 + the number of active resizing threads).  Otherwise,* when table is null, holds the initial table size to use upon* creation, or 0 for default. After initialization, holds the* next element count value upon which to resize the table.*/private transient volatile int sizeCtl;  /*** Creates a new, empty map with the default initial table size (16).*/public ConcurrentHashMap() {}/*** Creates a new, empty map with an initial table size* accommodating the specified number of elements without the need* to dynamically resize.** @param initialCapacity The implementation performs internal* sizing to accommodate this many elements.* @throws IllegalArgumentException if the initial capacity of* elements is negative*/public ConcurrentHashMap(int initialCapacity) {if (initialCapacity < 0)throw new IllegalArgumentException();int cap = ((initialCapacity >= (MAXIMUM_CAPACITY >>> 1)) ?MAXIMUM_CAPACITY :tableSizeFor(initialCapacity + (initialCapacity >>> 1) + 1));this.sizeCtl = cap;}

put()方法

具体调用了putVal(),依旧还是和putIfAbsent()调用的是同一个方法,ConcurrentHashMap容器初始化实在put()方法中加载的即initTable();方法;

这个版本计算hash值的方法为spread(object.hashCode()),在创建完table数组之后,接下来就是创建数组中的Node节点了,会判断当前是链表还是红黑树,然后将数据插入到对应的链表或树中,链表插入一个数据binCount就会自增,然后当这个值大于一个阈值时就会进入到链表转红黑树方法treeifyBin

    /*** Initializes table, using the size recorded in sizeCtl.*/
//采用了CAS设置了sizeCtl的值private final Node<K,V>[] initTable() {Node<K,V>[] tab; int sc;while ((tab = table) == null || tab.length == 0) {if ((sc = sizeCtl) < 0)Thread.yield(); // lost initialization race; just spinelse if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) {try {if ((tab = table) == null || tab.length == 0) {int n = (sc > 0) ? sc : DEFAULT_CAPACITY;@SuppressWarnings("unchecked")//创建table数组Node<K,V>[] nt = (Node<K,V>[])new Node<?,?>[n];table = tab = nt;//sc = 0.75n,即扩容因子还是0.75sc = n - (n >>> 2);}} finally {sizeCtl = sc;}break;}}return tab;}//计算key的hash值,与1.7相比,更加均匀static final int spread(int h) {return (h ^ (h >>> 16)) & HASH_BITS;}
/** Implementation for put and putIfAbsent */final V putVal(K key, V value, boolean onlyIfAbsent) {if (key == null || value == null) throw new NullPointerException();int hash = spread(key.hashCode());int binCount = 0;for (Node<K,V>[] tab = table;;) {Node<K,V> f; int n, i, fh;if (tab == null || (n = tab.length) == 0)tab = initTable();else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) {if (casTabAt(tab, i, null,new Node<K,V>(hash, key, value, null)))break;                   // no lock when adding to empty bin}else if ((fh = f.hash) == MOVED)tab = helpTransfer(tab, f);else {V oldVal = null;synchronized (f) {if (tabAt(tab, i) == f) {if (fh >= 0) {//进入到链表binCount = 1;for (Node<K,V> e = f;; ++binCount) {K ek;if (e.hash == hash &&((ek = e.key) == key ||(ek != null && key.equals(ek)))) {oldVal = e.val;if (!onlyIfAbsent)e.val = value;break;}Node<K,V> pred = e;if ((e = e.next) == null) {pred.next = new Node<K,V>(hash, key,value, null);break;}}}else if (f instanceof TreeBin) {//进入到红黑树Node<K,V> p;binCount = 2;if ((p = ((TreeBin<K,V>)f).putTreeVal(hash, key,value)) != null) {oldVal = p.val;if (!onlyIfAbsent)p.val = value;}}}}if (binCount != 0) {if (binCount >= TREEIFY_THRESHOLD)treeifyBin(tab, i);if (oldVal != null)return oldVal;break;}}}addCount(1L, binCount);return null;}/*** Replaces all linked nodes in bin at given index unless table is* too small, in which case resizes instead.*///将Node<>[]中的链表换成红黑树的TreeBinprivate final void treeifyBin(Node<K,V>[] tab, int index) {Node<K,V> b; int n, sc;if (tab != null) {if ((n = tab.length) < MIN_TREEIFY_CAPACITY)tryPresize(n << 1);else if ((b = tabAt(tab, index)) != null && b.hash >= 0) {synchronized (b) {if (tabAt(tab, index) == b) {TreeNode<K,V> hd = null, tl = null;for (Node<K,V> e = b; e != null; e = e.next) {TreeNode<K,V> p =new TreeNode<K,V>(e.hash, e.key, e.val,null, null);if ((p.prev = tl) == null)hd = p;elsetl.next = p;tl = p;}setTabAt(tab, index, new TreeBin<K,V>(hd));}}}}}

在put()的时候有个扩容的方法helpTransfer(tab, f); 

    /*** Helps transfer if a resize is in progress.*/final Node<K,V>[] helpTransfer(Node<K,V>[] tab, Node<K,V> f) {Node<K,V>[] nextTab; int sc;if (tab != null && (f instanceof ForwardingNode) &&(nextTab = ((ForwardingNode<K,V>)f).nextTable) != null) {int rs = resizeStamp(tab.length);while (nextTab == nextTable && table == tab &&(sc = sizeCtl) < 0) {if ((sc >>> RESIZE_STAMP_SHIFT) != rs || sc == rs + 1 ||sc == rs + MAX_RESIZERS || transferIndex <= 0)break;if (U.compareAndSwapInt(this, SIZECTL, sc, sc + 1)) {//扩容table数组transfer(tab, nextTab);break;}}return nextTab;}return table;}

get()

首先获取到key值的hash值,然后去定位是数组中的哪个Node节点,然后去遍历链表或者红黑树查找;

    public V get(Object key) {Node<K,V>[] tab; Node<K,V> e, p; int n, eh; K ek;int h = spread(key.hashCode());//获取key的对应的hash值if ((tab = table) != null && (n = tab.length) > 0 &&(e = tabAt(tab, (n - 1) & h)) != null) {if ((eh = e.hash) == h) {//判断是否为当前数组元素if ((ek = e.key) == key || (ek != null && key.equals(ek)))return e.val;}//从链表中获取数据else if (eh < 0)return (p = e.find(h, key)) != null ? p.val : null;//从红黑树中获取while ((e = e.next) != null) {if (e.hash == h &&((ek = e.key) == key || (ek != null && key.equals(ek))))return e.val;}}return null;}

结语:这玩意难度有点高啊,想要真正的看懂还需努力!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/537165.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

simulink显示多个数据_如何在 Simulink 中使用 PID Tuner 进行 PID 调参?

作者 | 安布奇责编 | 胡雪蕊出品 | CSDN(ID: CSDNnews)本文为一篇技术干货&#xff0c;主要讲述在Simulink如何使用PID Tuner进行PID调参。PID调参器( PIDTuner)概述1.1 简介使用PID Tuner可以对Simulink模型中的PID控制器&#xff0c;离散PID控制器&#xff0c;两自由度PID控制…

Java并发编程之堵塞队列介绍以及SkipList(跳表)

堵塞队列 先了解一下生产者消费者模式&#xff1a; 生产者就是生产数据的一方&#xff0c;消费者就是消费数据的另一方。在多线程开发中&#xff0c;如果生产者处理速度很快&#xff0c;而消费者处理速度很慢&#xff0c;那么生产者就必须等待消费者处理完&#xff0c;才能继…

python生成list的时候 可以用lamda也可以不用_python 可迭代对象,迭代器和生成器,lambda表达式...

分页查找#5.随意写一个20行以上的文件(divmod)# 运行程序&#xff0c;先将内容读到内存中&#xff0c;用列表存储。# l []# 提示&#xff1a;一共有多少页# 接收用户输入页码&#xff0c;每页5条&#xff0c;仅输出当页的内容def read_page(bk_list,n,endlineNone):startline …

数据挖掘技术简介[转]

关键词&#xff1a; 关键词&#xff1a;数据挖掘 数据集合 1. 引言  数据挖掘(Data Mining)是从大量的、不完全的、有噪声的、模糊的、随机的数据中提取隐含在其中的、人们事先不知道的、但又是潜在有用的信息和知识的过程。随…

树莓派安装smbus_树莓派使用smbus不兼容问题(no module named 'smbus')

树莓派使用smbus不兼容问题(no module named ‘smbus’)python3.5–3.6可以使用smbus2代替smbus1. 先参考以下方法&#xff1a;github讨论树莓派社区2.Pypi上可以下载smbus2smbus2PyPi介绍&#xff1a;当前支持的功能有&#xff1a;获取i2c功能(I2C_FUNCS)read_bytewrite_byter…

Java并发编程之线程池ThreadPoolExecutor解析

线程池存在的意义 平常使用线程即new Thread()然后调用start()方法去启动这个线程&#xff0c;但是在频繁的业务情况下如果在生产环境大量的创建Thread对象是则会浪费资源&#xff0c;不仅增加GC回收压力&#xff0c;并且还浪费了时间&#xff0c;创建线程是需要花时间的&…

面向过程的门面模式

{*******************************************************}{ }{ 业务逻辑一 }{ }{ 版权所有 (C) 2008 陈…

Java并发编程之线程定时器ScheduledThreadPoolExecutor解析

定时器 就是需要周期性的执行任务&#xff0c;也叫调度任务&#xff0c;在JDK中有个类Timer是支持周期性执行&#xff0c;但是这个类不建议使用了。 ScheduledThreadPoolExecutor 继承自ThreadPoolExecutor线程池&#xff0c;在Executors默认创建了两种&#xff1a; newSin…

python xml转换键值对_Python 提取dict转换为xml/json/table并输出

#!/usr/bin/python#-*- coding:gbk -*-#设置源文件输出格式import sysimport getoptimport jsonimport createDictimport myConToXMLimport myConToTabledef getRsDataToDict():#获取控制台中输入的参数&#xff0c;并根据参数找到源文件获取源数据csDict{}try:#通过getopt获取…

应用开发框架之——根据数据表中的存储的方法名称来调用方法

功用一&#xff1a;在框架里面根据存储在数据表中的方法名来动态调用执行方法。 unit Unit1; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; type TForm1 class(TForm) Button1: TButton; procedu…

Spring IOC容器组件注入的几种方式

整理一下之前Spring的学习笔记&#xff0c;大致有一下几种Spring注入到容器中的方法: 1&#xff09;、配置在xml的方式。 2&#xff09;、开启包扫描ComponentScan使用Component&#xff0c;Service&#xff0c;Controller&#xff0c;Repository&#xff08;其实后三个都继承…

我们是如何拿下Google和Facebook Offer的?

http://posts.careerengine.us/p/57c3a1c1a09633ee7e57803c 大家好&#xff0c;我是小高&#xff0c;CMU CS Master&#xff0c;来Offer第一期学员&#xff0c;2014年初在孙老师的带领下我在几个月的时间内进入了Yahoo&#xff0c;并工作了近2年。2016年初&#xff0c;Yahoo工作…

Spring中BeanFactory和FactoryBean的区别

先介绍一下Spring的IOC容器到底是个什么东西&#xff0c;都说是一个控制反转的容器&#xff0c;将对象的控制权交给IOC容器&#xff0c;其实在看了源代码之后&#xff0c;就会发现IOC容器只是一个存储单例的一个ConcurrentHashMap<String, BeanDefinition> BeanDefiniti…

python中数字和字符串可以直接相加_用c语言或者python将文件中特定字符串后面的数字相加...

匿名用户1级2014-08-31 回答代码应该不难吧。既然用爬虫爬下来了&#xff0c;为什么爬取数据的时候没做处理呢。之前用过Scrapy爬虫框架&#xff0c;挺好用的&#xff0c;你可研究下。代码&#xff1a;#!codingutf-8import osimport reimport random# 获取当前目录文件列表def …

Spring中Aware的用法以及实现

Aware 在Spring当中有一些内置的对象是未开放给我们使用的&#xff0c;例如Spring的上下文ApplicationContext、环境属性Environment&#xff0c;BeanFactory等等其他的一些内置对象&#xff0c;而在我们可以通过实现对应的Aware接口去拿到我们想要的一些属性&#xff0c;一般…

c#字符型转化为asc_C#字符串和ASCII码的转换

//字符转ASCII码&#xff1a;public static int Asc(string character){if (character.Length 1){System.Text.ASCIIEncoding asciiEncoding new System.Text.ASCIIEncoding();int intAsciiCode (int)asciiEncoding.GetBytes(character)[0];return (intAsciiCode);}else{thr…

topcoder srm 625 div1

problem1 link 假设第$i$种出现的次数为$n_{i}$&#xff0c;总个数为$m$&#xff0c;那么排列数为$T\frac{m!}{\prod_{i1}^{26}(n_{i}!)}$ 然后计算回文的个数&#xff0c;只需要考虑前一半&#xff0c;得到个数为$R$&#xff0c;那么答案为$\frac{R}{T}$. 为了防止数字太大导致…

Spring的组件赋值以及环境属性@PropertySource

PropertySource 将指定类路径下的.properties一些配置加载到Spring当中&#xff0c; 有个跟这个差不多的注解PropertySources Target(ElementType.TYPE) Retention(RetentionPolicy.RUNTIME) Documented public interface PropertySources {PropertySource[] value();} 使用…

python语音识别框架_横评:五款免费开源的语音识别工具

编者按&#xff1a;本文原作者 Cindi Thompson&#xff0c;美国德克萨斯大学奥斯汀分校(University of Texas at Austin)计算机科学博士&#xff0c;数据科学咨询公司硅谷数据科学(Silicon Valley Data Science&#xff0c;SVDS)首席科学家&#xff0c;在机器学习、自然语言处理…