为保证线程安全,经常用到的有内置锁synchronized和ReentrantLock。这两种是明显的互斥锁,每次最多只能有一个线程拥有锁。使用互斥锁可以有效避免“写读冲突”、“写写冲突”、“读读冲突”,从而保证线程安全。但是,很明显,“读读冲突”是不需要避免的,因为多个线程读并不会·出现线程安全问题。如果在读操作比较多的情景下,使用互斥锁,则会显得过于保守强硬,从而抑制了性能。因此引入了一种优化的锁,叫做读写锁,该锁主要表示:一个资源可以被多个读操作访问或者被一个写操作访问,且两者不能同时进行。这样对于读操作访问比较密集的数据结构,则大大提升了并发性能,提升了可伸缩性。
读写锁实现ReadWriteLock接口,典型的有ReentrantReadWriteLock。接下来对该读写锁进行源码分析,并进行示例实现。
1.源码解析
首先来看读写锁的基础接口:ReadWriteLock。该接口总共两个抽象方法,分别是readLock()和writeLock(),两个方法返回类型都是Lock类型,说明两者返回的是锁,分别是读锁和写锁。
public interface ReadWriteLock {
/**
* Returns the lock used for reading.
*
* @return the lock used for reading
*/
Lock readLock();
/**
* Returns the lock used for writing.
*
* @return the lock used for writing
*/
Lock writeLock();
}
接下来看ReentrantReadWriteLock,该类扩展了ReadWriteLock接口。
首先是构造方法
*/
public ReentrantReadWriteLock() {
this(false);
}
/**
* Creates a new {@code ReentrantReadWriteLock} with
* the given fairness policy.
*
* @param fair {@code true} if this lock should use a fair ordering policy
*/
public ReentrantReadWriteLock(boolean fair) {
sync = fair ? new FairSync() : new NonfairSync();
readerLock = new ReadLock(this);
writerLock = new WriteLock(this);
}
构造方法中可以传入一个参数,fair值表示公平模式还是非公平模式,一般默认值是非公平模式。
然后是接口中两个方法的实现
public ReentrantReadWriteLock.WriteLock writeLock() { return writerLock; }
public ReentrantReadWriteLock.ReadLock readLock() { return readerLock; }
而writerLock和readerLock是内部类ReadLock和WriteLock的对象。其中ReadLock和WriteLock实现了Lock接口以及实现了接口中的方法。
以下是WriteLock部分源码:
protected WriteLock(ReentrantReadWriteLock lock) {
sync = lock.sync;
}
/**
* Acquires the write lock.
*
* <p>Acquires the write lock if neither the read nor write lock
* are held by another thread
* and returns immediately, setting the write lock hold count to
* one.
*
* <p>If the current thread already holds the write lock then the
* hold count is incremented by one and the method returns
* immediately.
*
* <p>If the lock is held by another thread then the current
* thread becomes disabled for thread scheduling purposes and
* lies dormant until the write lock has been acquired, at which
* time the write lock hold count is set to one.
*/
public void lock() {
sync.acquire(1);
}
以下是ReadLock部分源码:
protected ReadLock(ReentrantReadWriteLock lock) {
sync = lock.sync;
}
/**
* Acquires the read lock.
*
* <p>Acquires the read lock if the write lock is not held by
* another thread and returns immediately.
*
* <p>If the write lock is held by another thread then
* the current thread becomes disabled for thread scheduling
* purposes and lies dormant until the read lock has been acquired.
*/
public void lock() {
sync.acquireShared(1);
}
可以看出读锁使用了共享模式,而写锁使用的是独占锁的模式,这也就是读写锁的特点。
2.示例讲解
假设有一个读操作频繁的Map,可以通过读写锁包装的Map来提升并发性能。具体代码如下:
package factorialtail;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class ReadWriteMap<K, V> {
private final Map<K, V> map;
private final ReadWriteLock lock=new ReentrantReadWriteLock();
private final Lock read=lock.readLock();
private final Lock write=lock.writeLock();
public ReadWriteMap(Map<K, V> map) {
// TODO Auto-generated constructor stub
this.map=map;
}
public V put(K key,V value)
{
write.lock();//写锁
try {
return map.put(key, value);
}
finally {
write.unlock();
}
}
public V get(Object key)
{
read.lock();//读锁
try {
return map.get(key);
}
finally {
read.unlock();
}
}
}
测试案例:
package factorialtail;
import java.util.HashMap;
import java.util.Map;
public class ReadWriteLockTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
final Map<String, Integer> map=new HashMap<>();
final ReadWriteMap<String, Integer> rwMap=new ReadWriteMap<>(map);
rwMap.put("a", 1);
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
rwMap.put("b", 2);
}
}).start();
for(int i=0;i<20;i++)
{
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println("i="+((int)rwMap.get("a")+1));
}
}).start();
}
}
}
以上便是读写锁一个简单例子。