From this question How to understand the “non-fair” mode of ReentrantReadWriteLock?, I think all threads have the same opportunity to get the lock no matter which comes first.
So I write this code to test it:
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();
}
}
At first, there is a thread got the write lock, and held it for 3s. During this time, a thread want to get the read lock, and then 1000 threads want to get the write lock.
Since ReentrantReadWriteLock uses non-fair mode by default, I think the write threads have a great opportunity to get the write lock. But I run it many times, and each time read thread won!
The output is:
Thread-0 got the write lock
Thread-0 released the write lock
Thread-1 got the read lock
Do I understanding "non-fair" wrong?
UPDATE Per paxdiablo's answer, I modified my code to:
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();
}
Now there is a thread want the write lock and 1000 read threads want the read lock. But the output is:
Thread-0 got the write lock
Thread-0 released the write lock
Thread-1 got the write lock
Seem it's still "first-come-first-get".