How to master the core foundation of java ConcurrentHashMap
Today, the editor will share with you the relevant knowledge points about how to master the core foundation of java ConcurrentHashMap. The content is detailed and the logic is clear. I believe most people still know too much about this knowledge, so share this article for your reference. I hope you can get something after reading this article. Let's take a look.
1 preface
ConcurrentHashMap is a Map interface implementation based on Hash table. Keys and values are not allowed to be NULL. It is a thread-safe Map. At the same time, it is also a disordered Map, traversing at different times may get a different order. Before JDK1.8, ConcurrentHashMap used segmented locks to achieve greater efficiency while ensuring thread safety. JDK1.8 began to abandon segmented locks and use the spin + CAS+sync keyword to achieve synchronization. This article is based on JDK1.8.
ConcurrentHashMap and HashMap have something in common, some of the basic concepts and implementation of HashMap, this article will not repeat.
2 inheritance relationship public class ConcurrentHashMap extends AbstractMap implements ConcurrentMap, Serializable
You can see that ConcurrentHashMap inherits the AbstractMap and ConcurrentMap abstract classes and implements the Serializable interface, which shows that ConcurrentHashMap is a thread-safe standard Map and allows serialization. Unlike HashMap, ConcurrentHashMap does not allow Clone.
(3) Construction method
ConcurrentHashMap also uses lazy initialization, initializing the container only when there are actual elements. Therefore, its construction method is similar to that of HashMap.
/ / No-parameter construction public ConcurrentHashMap () {} / / Construction public ConcurrentHashMap (int initialCapacity) {if (initialCapacity) with initial capacity
< 0) throw new IllegalArgumentException(); int cap = ((initialCapacity >= (MAXIMUM_CAPACITY > 1)? MAXIMUM_CAPACITY: tableSizeFor (initialCapacity + (initialCapacity > > 1) + 1); / / find the least quadratic power this.sizeCtl = cap; / / sizeCtl temporary storage capacity} / / construct public ConcurrentHashMap with initial set (Map)