ReadWriteLock
来源:互联网 发布:那个漫画软件好最全 编辑:程序博客网 时间:2024/06/03 12:41
- ReadWriteLock Locking Rules
- ReadWriteLock Implementations
- ReadWriteLock Code Example
A java.util.concurrent.locks.ReadWriteLock
is an advanced thread lock mechanism. It allows multiple threads to read a certain resource, but only one to write it, at a time.
The idea is, that multiple threads can read from a shared resource without causing concurrency errors. The concurrency errors first occur when reads and writes to a shared resource occur concurrently, or if multiple writes take place concurrently.
In this text I only cover Java's built-in ReadWriteLock
. If you want to read more about the theory behind the implemenation of a ReadWriteLock, you can read it in my text on Read Write Locks in my Java Concurrency tutorial.
ReadWriteLock Locking Rules
The rules by which a thread is allowed to lock the ReadWriteLock
either for reading or writing the guarded resource, are as follows:
ReadWriteLock
for writing, and no thread have requested a write lock (but not yet obtained it).
Thus, multiple threads can lock the lock for reading.
Thus, only one thread at a time can lock the lock for writing.
ReadWriteLock Implementations
ReadWriteLock
is an interface. Thus, to use a ReadWriteLock
The java.util.concurrent.locks
package contains the following ReadWriteLock
implementation:
- ReentrantReadWriteLock
ReadWriteLock Code Example
Here is a simple code example that shows how to create a ReadWriteLock
and how to lock it for reading and writing:
ReadWriteLock readWriteLock = new ReentrantReadWriteLock();readWriteLock.readLock().lock(); // multiple readers can enter this section // if not locked for writing, and not writers waiting // to lock for writing.readWriteLock.readLock().unlock();readWriteLock.writeLock().lock(); // only one writer can enter this section, // and only if no threads are currently reading.readWriteLock.writeLock().unlock();
Notice how the ReadWriteLock
actually internally keeps two Lock
instances. One guarding read access, and one guarding write access.
- ReadWriteLock
- ReadWriteLock
- ReadWriteLock
- ReadWriteLock
- ReadWriteLock
- ReadWriteLock
- 浅谈ReadWriteLock
- ReadWriteLock用法
- ReadWriteLock用法
- ReadWriteLock用法
- ReadWriteLock用法
- ReadWriteLock使用
- ReadWriteLock用法
- ReadWriteLock用法
- ReadWriteLock是什么?
- 可重入锁 -- ReadWriteLock
- 线程ReadWriteLock 读写锁
- JDK5 读写锁 ReadWriteLock
- 第7周项目3 计算量正整数的正差值
- Handler详解系列(八)——Handler与Toast以及其它杂项
- JSF学习一 下载
- 改善羽毛球比赛心理有“妙招”
- 网络处理的软中断机制分析
- ReadWriteLock
- fedora 20 telnet服务器端的安装
- POJ 2114 Boatherds 树的分治
- Pascal's Triangle
- 使用Java实现文件内容的写入读出
- Handler详解系列(七)——Activity.runOnUiThread()方法详解
- 深入浅出UML类图
- dojo chart生成函数
- 第七周项目一串联电阻