この質問からReentrantReadWriteLock の「不公平な」モードを理解する方法は? 、どのスレッドが先に来ても、すべてのスレッドがロックを取得する機会は同じだと思います。
だから私はそれをテストするためにこのコードを書きます:
public static void main(String[] args) {
ReentrantReadWriteLock lock = new ReentrantReadWriteLock(true);
final ReadLock readLock = lock.readLock();
final WriteLock writeLock = lock.writeLock();
// hold the write lock 3s at first
new Thread() {
public void run() {
writeLock.lock();
System.out.println(Thread.currentThread().getName() + " got the write lock");
quietSleep(3);
writeLock.unlock();
System.out.println(Thread.currentThread().getName() + " released the write lock");
};
}.start();
// a thread want to get the read lock 1s later
new Thread() {
public void run() {
quietSleep(1);
readLock.lock();
System.out.println(Thread.currentThread().getName() + " got the read lock");
};
}.start();
// 1000 threads want to get the write lock 2s later
for (int i = 0; i < 1000; i++) {
new Thread() {
public void run() {
quietSleep(2);
writeLock.lock();
System.out.println(Thread.currentThread().getName() + " got the write lock");
};
}.start();
}
}
private static void quietSleep(int seconds) {
try {
Thread.sleep(seconds * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
最初に、スレッドが書き込みロックを取得し、それを 3 秒間保持しました。この間、1 つのスレッドが読み取りロックを取得しようとし、次に 1000 のスレッドが書き込みロックを取得しようとします。
ReentrantReadWriteLock はデフォルトで非公平モードを使用するため、書き込みスレッドが書き込みロックを取得する絶好の機会があると思います。しかし、私はそれを何度も実行し、そのたびに読み取りスレッドが勝ちました!
出力は次のとおりです。
Thread-0 got the write lock
Thread-0 released the write lock
Thread-1 got the read lock
「不公平」の理解は間違っていますか?
更新 paxdiabloの回答に従って、コードを次のように変更しました。
new Thread() {
public void run() {
quietSleep(1);
writeLock.lock();
System.out.println(Thread.currentThread().getName() + " got the write lock");
};
}.start();
for (int i = 0; i < 1000; i++) {
new Thread() {
public void run() {
quietSleep(2);
readLock.lock();
System.out.println(Thread.currentThread().getName() + " got the read lock");
};
}.start();
}
現在、書き込みロックを必要とするスレッドがあり、1000 の読み取りスレッドが読み取りロックを必要としています。しかし、出力は次のとおりです。
Thread-0 got the write lock
Thread-0 released the write lock
Thread-1 got the write lock
まだ「先着順」のようです。