1.hashmap如果要保证同步,该如何实现
![在这里插入图片描述](https://img-blog.csdnimg.cn/20200920101717911.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzM3ODAyNjM3,size_16,color_FFFFFF,t_70#pic_cente
我们知道,如果多个线程同时访问hashtable时候,hashtable是直接将此对象锁起来。加入hashmap也按照hashtable这种方式来实现,即put、remove等方法上加一个syncronzed关键字。这种情况效率肯定不高。如上图,如果把hashmap分成一段一段的,加入一个12:1这个值,你会发现受影响的只是倒数第二段,其他的段里的操作不会受印象。所以concurrentHashMap加入了段的概念来优化性能。
2.concurrentHashMap结构
此构造方法第一个参数表示默认初始化容量16,表示ConcurrentHashMap的初始化容量大小,在hashmap里由于
在初始化数组时候会调用,table = new Entry[capacity];(capacity已经被设置为了2的幂)此方法,所以数组大小默认也为16,
但是在concurrenthashmap中
,第二个表示默认初始化负载因子0.75,第三个参数表示默认并发级别,也就是concurrenthashmap有多少段,默认16段。
public ConcurrentHashMap(int initialCapacity,
float loadFactor, int concurrencyLevel) {
if (!(loadFactor > 0) || initialCapacity < 0 || concurrencyLevel <= 0)
throw new IllegalArgumentException();
if (concurrencyLevel > MAX_SEGMENTS)
concurrencyLevel = MAX_SEGMENTS;
// Find power-of-two sizes best matching arguments
int sshift = 0;
int ssize = 1; // 1
while (ssize < concur