ReadWriteLock使得你可以同时具有多个读取者,只要他们都不试图写入即可。如果写锁被其他任务持有,那么任何读取者均不能访问,直至这个写锁被释放为止。
ReadWriteLock能否提高性能是不确定的,取决于数据读取与修改频率相比较的结果,读取和写入操作的时间,竞争的线程数以及是否是多处理器等等。
下面展示了ReadWriteLock最基本的用法。
程序输出结果如下:
24
25
22
19
17
16
...
...//省略
7
6
5
4
3
Writer finished, shutting down
set()方法获取写锁,get方法获取读锁,并且检查是否有多个线程获取了读锁,如果是就打印这种读取者的数量到控制台,以证明可以有多个读取者获得读锁。
ReadWriteLock能否提高性能是不确定的,取决于数据读取与修改频率相比较的结果,读取和写入操作的时间,竞争的线程数以及是否是多处理器等等。
下面展示了ReadWriteLock最基本的用法。
package concurrency;
//: concurrency/ReaderWriterList.java
import java.util.concurrent.*;
import java.util.concurrent.locks.*;
import java.util.*;
public class ReaderWriterList<T> {
private ArrayList<T> lockedList;
// Make the ordering fair:
private ReentrantReadWriteLock lock = new ReentrantReadWriteLock(true);
public ReaderWriterList(int size, T initialValue) {
lockedList = new ArrayList<T>(Collections.nCopies(size, initialValue));
}
public T set(int index, T element) {
Lock wlock = lock.writeLock();
wlock.lock();
try {
return lockedList.set(index, element);
} finally {
wlock.unlock();
}
}
public T get(int index) {
Lock rlock = lock.readLock();
rlock.lock();
try {
// Show that multiple readers
// may acquire the read lock:
if (lock.getReadLockCount() > 1)
System.out.println(lock.getReadLockCount());
return lockedList.get(index);
} finally {
rlock.unlock();
}
}
public static void main(String[] args) throws Exception {
new ReaderWriterListTest(30, 1);
}
}
class ReaderWriterListTest {
ExecutorService exec = Executors.newCachedThreadPool();
private final static int SIZE = 100;
private static Random rand = new Random(47);
private ReaderWriterList<Integer> list = new ReaderWriterList<Integer>(
SIZE, 0);
private class Writer implements Runnable {
public void run() {
try {
for (int i = 0; i < 20; i++) { // 2 second test
list.set(i, rand.nextInt());
TimeUnit.MILLISECONDS.sleep(100);
}
} catch (InterruptedException e) {
// Acceptable way to exit
}
System.out.println("Writer finished, shutting down");
exec.shutdownNow();
}
}
private class Reader implements Runnable {
public void run() {
try {
while (!Thread.interrupted()) {
for (int i = 0; i < SIZE; i++) {
list.get(i);
TimeUnit.MILLISECONDS.sleep(1);
}
}
} catch (InterruptedException e) {
// Acceptable way to exit
}
}
}
public ReaderWriterListTest(int readers, int writers) {
for (int i = 0; i < readers; i++)
exec.execute(new Reader());
for (int i = 0; i < writers; i++)
exec.execute(new Writer());
}
} /* (Execute to see output) */// :~
程序输出结果如下:
24
25
22
19
17
16
...
...//省略
7
6
5
4
3
Writer finished, shutting down
set()方法获取写锁,get方法获取读锁,并且检查是否有多个线程获取了读锁,如果是就打印这种读取者的数量到控制台,以证明可以有多个读取者获得读锁。