我正在寻找一种解决方案,允许多个线程读取共享资源(允许并发),但一旦线程进入变异块就会锁定这些读取线程,以实现两全其美。
class Foo {
Map<String, String> sharedResource;
public void read() // multiple reading threads allowed, concurrency ok, lock this only if a thread enters the mutating block below.
{
// read concurrently unless a thread enters mutating blocks add/remove
}
public void add() // this should lock any threads entering this block as well as lock the reading threads above
{
synchronized(sharedResource) // lock remove and read
{
}
}
public void remove() // lock add and read
{
synchronized(sharedResource)
{
}
}
}
Java中是否有这样的解决方案?
答案 0 :(得分:4)
这是一个经典的读/写锁定方案:
class Foo {
Map<String, String> sharedResource;
ReadWriteLock lock = new ReentrantReadWriteLock();
public void read() {
lock.readLock().lock();
try {
// read
} finally {
lock.readLock().unlock();
}
}
public void add() {
lock.writeLock().lock();
try {
// add
} finally {
lock.writeLock().unlock();
}
}
public void remove() {
lock.writeLock().lock();
try {
// remove
} finally {
lock.writeLock().unlock();
}
}
}
可以共享读锁定,但写锁定对读取和写入都是唯一的。