ReadWriteLock
public interface ReadWriteLock
java.util.concurrent.locks.ReadWriteLock |
Known Indirect Subclasses
|
A ReadWriteLock
维护一对关联的locks
,一个用于只读操作,另一个用于写入。 只要没有作家, read lock可能会被多个阅读器线程同时持有。 write lock是排他性的。
所有的ReadWriteLock
实现都必须保证writeLock
操作(如Lock
接口中指定的)的内存同步效果也可以保持与关联的readLock
相关。 也就是说,成功获取读锁的线程将看到在前一次释放写锁时所做的所有更新。
读写锁允许访问共享数据的并发性水平高于互斥锁允许的水平。 它利用了这样一个事实,即一次只有一个线程(一个编写器线程)可以修改共享数据,在很多情况下,任何数量的线程都可以同时读取数据(因此读取器线程)。 理论上,使用读写锁定所允许的并发性增加将导致性能提高超过使用互斥锁。 实际上,这种并发性的增加只能在多处理器上完全实现,并且只有在共享数据的访问模式合适时才会如此。
读写锁是否会提高使用互斥锁的性能取决于数据读取的频率与被修改的频率,读取和写入操作的持续时间以及数据的争用 - 是,将尝试同时读取或写入数据的线程数。 例如,一个最初用数据填充并且此后不经常修改,而频繁搜索(例如某种目录)的集合是使用读写锁定的理想候选。 然而,如果更新变得频繁,那么数据的大部分时间都被锁定,并且几乎没有并发的增加。 此外,如果读取操作太短,则读写锁定实现(本质上比互斥锁定更复杂)的开销可以支配执行成本,特别是因为许多读写锁定实现仍然通过小部分代码。 最终,只有分析和测量才能确定使用读写锁是否适合您的应用程序。
尽管读写锁的基本操作很简单,但实现必须作出许多策略决策,这可能会影响给定应用程序中读写锁的有效性。 这些政策的例子包括:
- Determining whether to grant the read lock or the write lock, when both readers and writers are waiting, at the time that a writer releases the write lock. Writer preference is common, as writes are expected to be short and infrequent. Reader preference is less common as it can lead to lengthy delays for a write if the readers are frequent and long-lived as expected. Fair, or "in-order" implementations are also possible.
- Determining whether readers that request the read lock while a reader is active and a writer is waiting, are granted the read lock. Preference to the reader can delay the writer indefinitely, while preference to the writer can reduce the potential for concurrency.
- Determining whether the locks are reentrant: can a thread with the write lock reacquire it? Can it acquire a read lock while holding the write lock? Is the read lock itself reentrant?
- Can the write lock be downgraded to a read lock without allowing an intervening writer? Can a read lock be upgraded to a write lock, in preference to other waiting readers or writers?
You should consider all of these things when evaluating the suitability of a given implementation for your application.
Summary
Public methods
readLock
Lock readLock ()
返回用于读取的锁。
Returns |
Lock |
the lock used for reading |
writeLock
Lock writeLock ()
返回用于写入的锁。
Returns |
Lock |
the lock used for writing |