The following is the typical reader and writer pattern (a lot of reads and few writes)
private ReadWriteLock lock = new ReentrantReadWriteLock();
private int value;
public void writeValue(int newValue){
lock.writeLock().lock();
try{
this.value = newValue;
}
finally{
lock.writeLock().unlock();
}
}
public int readValue(){
lock.readLock().lock();
try{
return value;
}
finally{
lock.writeLock().unlock();
}
}
I am wondering that is it possible to have priority to writer and reader ? For example, normally writer could wait a very long time (maybe forever) if there are constantly read locks held by other thread, so is it possible to have writer with higher priority, so whenever a writer comes it can be considered as it's being as high priority (skip line) something like that.
According to the javadoc, the jdk implementation does not have any reader/writer priority. however, if you use the "fair" implementation, then the lock is granted in fifo order (still no reader/writer preference), so at least future readers will not block waiting writers.