ConcurrentHashMap&HashMap&Hashtable使用上的区别

夏沐沐

关注

阅读 62

2022-05-17


1、ConcurrentHashMap

区别1、使用了Lock分段锁,效率不高,默认的是非公平锁,利于多线程使用。

/**
* Creates a new {@code ReentrantReadWriteLock} with
* the given fairness policy.
*
* @param fair {@code true} if this lock should use a fair ordering policy
*/
public ReentrantReadWriteLock(boolean fair) {
sync = fair ? new FairSync() : new NonfairSync();
readerLock = new ReadLock(this);
writerLock = new WriteLock(this);
}

public ReentrantReadWriteLock.WriteLock writeLock() { return writerLock; }
public ReentrantReadWriteLock.ReadLock readLock() { return readerLock; }

区别2,在hash的算法上也是区别很大

protected static int hash(int h) {
h += h << 15 ^ -12931;
h ^= h >>> 10;
h += h << 3;
h ^= h >>> 6;
h += (h << 2) + (h << 14);
return h ^ h >>> 16;
}

区别三,不允许key与Value为null。在put的时候判别。


精彩评论(0)

0 0 举报