Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Example Analysis of ConcurrentHashMap Source Code of java concurrent package

2025-01-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly introduces the java concurrent package ConcurrentHashMap source code example analysis, the article introduces in great detail, has a certain reference value, interested friends must read it!

The realization of JDK1.7

The whole ConcurrentHashMap consists of Segment, and Segment stands for "part" or "segment", so it is described as segmented lock in many places. Note that I use "slot" to represent a segment in many places in the text.

To put it simply, ConcurrentHashMap is an Segment array, and Segment adds locks by inheriting ReentrantLock, so each operation that needs to be locked locks a segment, so as long as each Segment is thread-safe, global thread safety is achieved.

ConcurrencyLevel: parallel level, number of concurrency, number of Segment. The default is 16, which means that ConcurrentHashMap has 16 Segments, so in theory, at this time, you can support up to 16 threads writing at the same time, as long as their operations are distributed on different Segment. This value can be set to other values during initialization, but once initialized, it cannot be expanded.

Inside each Segment, in fact, each Segment is very similar to the HashMap introduced earlier, but it needs to be thread-safe, so it's a bit more troublesome to deal with.

Initialization

InitialCapacity: initial capacity. This value refers to the initial capacity of the entire ConcurrentHashMap, which needs to be distributed equally to each Segment in practice.

LoadFactor: load factor, as we said earlier, the Segment array cannot be expanded, so this load factor is for internal use of each Segment.

Public ConcurrentHashMap (int initialCapacity, float loadFactor, int concurrencyLevel) {if (! (loadFactor > 0) | | initialCapacity

< 0 || concurrencyLevel MAX_SEGMENTS) concurrencyLevel = MAX_SEGMENTS; // Find power-of-two sizes best matching arguments int sshift = 0; int ssize = 1; // 计算并行级别 ssize,因为要保持并行级别是 2 的 n 次方 while (ssize < concurrencyLevel) { ++sshift; ssize segmentShift) & segmentMask; // 刚刚说了,初始化的时候初始化了 segment[0],但是其他位置还是 null, // ensureSegment(j) 对 segment[j] 进行初始化 if ((s = (Segment)UNSAFE.getObject // nonvolatile; recheck (segments, (j MAX_SCAN_RETRIES) { lock(); break; } else if ((retries & 1) == 0 && // 这个时候是有大问题了,那就是有新的元素进到了链表,成为了新的表头 // 所以这边的策略是,相当于重新走一遍这个 scanAndLockForPut 方法 (f = entryForHash(this, hash)) != first) { e = first = f; // re-traverse if entry changed retries = -1; } } return node;} 这个方法有两个出口,一个是 tryLock() 成功了,循环终止,另一个就是重试次数超过了 MAX_SCAN_RETRIES,进到 lock() 方法,此方法会阻塞等待,直到成功拿到独占锁。 这个方法就是看似复杂,但是其实就是做了一件事,那就是获取该 segment 的独占锁,如果需要的话顺便实例化了一下 node。 获取锁时,并不直接使用lock来获取,因为该方法获取锁失败时会挂起。事实上,它使用了自旋锁,如果tryLock获取锁失败,说明锁被其它线程占用,此时通过循环再次以tryLock的方式申请锁。如果在循环过程中该Key所对应的链表头被修改,则重置retry次数。如果retry次数超过一定值,则使用lock方法申请锁。 这里使用自旋锁是因为自旋锁的效率比较高,但是它消耗CPU资源比较多,因此在自旋次数超过阈值时切换为互斥锁。 扩容: rehash 重复一下,segment 数组不能扩容,扩容是 segment 数组某个位置内部的数组 HashEntry\[] 进行扩容,扩容后,容量为原来的 2 倍。 首先,我们要回顾一下触发扩容的地方,put 的时候,如果判断该值的插入会导致该 segment 的元素个数超过阈值,那么先进行扩容,再插值,读者这个时候可以回去 put 方法看一眼。 该方法不需要考虑并发,因为到这里的时候,是持有该 segment 的独占锁的。 // 方法参数上的 node 是这次扩容后,需要添加到新的数组中的数据。private void rehash(HashEntry node) { HashEntry[] oldTable = table; int oldCapacity = oldTable.length; // 2 倍 int newCapacity = oldCapacity >

> segmentShift) & segmentMask)

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 298

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report