Java:具有优先级的ReentrantReadWriteLock [英] Java : ReentrantReadWriteLock with priority
问题描述
以下是典型的读写器模式(大量读取和少量写入)
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.
推荐答案
根据 javadoc ,jdk实现不有任何读者/作家优先。但是,如果你使用公平实现,那么锁 以fifo顺序被授予(仍然没有读者/作者偏好),所以至少未来的读者不会阻止等待的作者。
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.
这篇关于Java:具有优先级的ReentrantReadWriteLock的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!