可重入锁定并发哈希表是否使用其可选的“公平”参数?

Ani*_*kur 3 java synchronization concurrenthashmap

在ConcurrentHashMap中,我们具有基本上扩展ReentrantLock的段。

static final class Segment<K,V> extends ReentrantLock implements Serializable
Run Code Online (Sandbox Code Playgroud)

这个ReentrantLock是否使用其公平属性?

public ReentrantLock(boolean fair) {
    sync = fair ? new FairSync() : new NonfairSync();
}
Run Code Online (Sandbox Code Playgroud)

因此,可以说线程t1在ConcurrentHashMap的一个分区上具有读取锁定,另外两个线程t2和t3在同一分区上分别等待读取和写入锁定。因此,一旦t1释放锁,哪个(t2或t3)将获得该锁。

据我所知,如果公平性设置为true,那将是等待时间最长的人。但是,在并发HashMap的情况下是否将其设置为true?如果不能,我们可以肯定地说哪个线程将获得下一个锁?

Evg*_*eev 5

从ConcurrentHashMap源代码中,我们可以看到它使用了ReentrantLock的子类。

static final class Segment<K,V> extends ReentrantLock
   ...
   Segment(float lf, int threshold, HashEntry<K,V>[] tab) {
            this.loadFactor = lf;
            this.threshold = threshold;
            this.table = tab;
   }
   ...
Run Code Online (Sandbox Code Playgroud)

如我们所见,其唯一的构造函数隐式调用ReentrantLock的no-args构造函数,该构造函数创建了非公平锁定。这意味着ConcurrentHashMap的锁总是不公平的