对于读取操作数量明显大于写入操作的场景,使用读写锁。
先来自己实现个读写锁,之后再分析JUC包下的ReentrantReadWriteLock。
读写锁的规则:当有写操作正在运行,则读操作应该等待;当有写操作正在运行,读操作也要等待。读操作与读操作之间不会阻塞,也就是读读可以,写读,写写都不行。
这里还有个问题那就是饥饿,于是我们有加了个变量用来记录写请求,每个读操作都会先检查会不会有写请求,于是就保证了读操作优先级大于写操作,对于有大量读操作的场景可以防止饥饿。
public class ReadWriteLock {
private int reader;
private int write;
private int writeRequests;
public synchronized void lockRead() throws InterruptedException {
while (write > 0 || writeRequests > 0) {
wait();
}
reader++;
}
public synchronized void unlockRead() {
reader--;
notifyAll();
}
public synchronized void lockWrite() throws InterruptedException {
writeRequests++;
while (reader > 0 || write > 0) {
wait();
}
writeRequests--;
write++;
}
public synchronized void unlockWrite() {
write--;
notifyAll();
}
}
但是仍有个问题没有解决,那就是死锁,上面的代码会造成死锁。例如A有读锁正在运行,B线程尝试获取写权限,之后回到A,A在代码中需要再次获取锁,但是它会阻塞因为writeRequests为1了,这样A不会结束,B同样不会被唤醒,死循环了。怎么办?加入重入逻辑!
重入
读读重入
private final Map readingThreads = new HashMap<>(); //存放的是获取读锁的线程
private int writeAccess; //记录获取写锁的线程个数
private int writeRequests; //请求写锁的线程个数
private Thread writingThread; //当前获取读锁线程
public synchronized void lockRead() throws InterruptedException {
Thread callingThread = Thread.currentThread();
while (!canGetReadAccess(callingThread)) {
wait();
}
readingThreads.put(callingThread, getReadAccessCount(callingThread) + 1);
}
public synchronized void unlockRead() {
Thread callingThread = Thread.currentThread();
int count = readingThreads.get(callingThread);
if (count == 1) {
readingThreads.remove(callingThread);
}else {
readingThreads.put(callingThread, count - 1);
}
notifyAll();
}
private boolean canGetReadAccess(Thread thread) {
if (writeAccess > 0) return false;
if (isReading(thread)) return true;
if (writeRequests > 0) return false;
return true;
}
private boolean isReading(Thread thread) {
return readingThreads.get(thread) != null;
}
private int getReadAccessCount(Thread thread) {
Integer count = readingThreads.get(thread);
if (count == null) return 0;
return count;
}
我们的重入逻辑便在canGetReadAccess中,可以看出如果当前持有读锁的线程再次尝试重入,其优先级要高于写请求。这就解决了上面死循环的问题。
写写重入
public synchronized void lockWrite() throws InterruptedException {
writeRequests++;
Thread callingThread = Thread.currentThread();
while (!canGetWriteAccess(callingThread)) {
wait();
}
writeRequests--;
writeAccess++;
writingThread = callingThread;
}
public synchronized void unlockWrite() {
writeAccess--;
if (writeAccess == 0) {
writingThread = null;
}
notifyAll();
}
private boolean canGetWriteAccess(Thread callingThread) {
if (hasReader()) return false;
if (writingThread == null) return true;
if (isWriting(callingThread)) return true;
return true;
}
private boolean isWriting(Thread callingThread) {
return callingThread == writingThread;
}
private boolean hasReader() {
return readingThreads.size() > 0;
}
二者实现不同是因为要求不同,读写锁多线程可以同时读,但是对于写来说同时只能有一个线程执行写。所以读读与写写的重入实现需要满足这种要求。
读写重入
只有一个读线程的情况下,允许该线程获取写权限
private boolean canGetWriteAccess(Thread callingThread) {
if (isOnlyReader(callingThread)) return true; //读写重入
if (hasReader()) return false;
if (writingThread == null) return true;
if (isWriting(callingThread)) return true;
return false;
}
private boolean isOnlyReader(Thread callingThread) {
return readingThreads.size() == 1 &&
readingThreads.get(callingThread) != null;
}
写读重入
写线程执行时,其他线程都得等待,所以并没有什么不安全
private boolean canGetReadAccess(Thread thread) {
if (isWriting(thread)) return true; //写线程运行时一定只有它一个线程运行,所以并没有危险
if (writeAccess > 0) return false;
if (isReading(thread)) return true; //读重入,放在写请求判断前,确保优先级比它高
if (writeRequests > 0) return false;
return true;
}
完整代码
/**
* 读重入:没有写操作或写操作请求,则读操作获得权限;如果是一个运行中的读操作可以再此获得读操作权限,无视写请求
* 写重入:如果没有读操作或者写操作,则写操作获得权限;
* 读写重入:只有一个读线程的情况下,允许该线程获取写权限
* 写读重入:写线程执行时,其他线程都得等待,所以并没有什么不安全
*
* 这里所设计的读与写获取的都是该类对象的锁,在JUC中的读写锁更加强大,它将锁的粒度分开,利用AQS
*/
public class ReadWriteLock2 {
private final Map readingThreads = new HashMap<>(); //存放的是获取读锁的线程
private int writeAccess; //记录获取写锁的线程个数
private int writeRequests; //请求写锁的线程个数
private Thread writingThread; //当前获取读锁线程
public synchronized void lockRead() throws InterruptedException {
Thread callingThread = Thread.currentThread();
while (!canGetReadAccess(callingThread)) {
wait();
}
readingThreads.put(callingThread, getReadAccessCount(callingThread) + 1);
}
public synchronized void unlockRead() {
Thread callingThread = Thread.currentThread();
if (!isReading(callingThread)) {
throw new IllegalMonitorStateException("该线程并没有获得该实例的读锁");
}
int count = getReadAccessCount(callingThread);
if (count == 1) {
readingThreads.remove(callingThread);
}else {
readingThreads.put(callingThread, count - 1);
}
notifyAll();
}
private boolean canGetReadAccess(Thread thread) {
if (isWriting(thread)) return true; //写线程运行时一定只有它一个线程运行,所以并没有危险
if (writeAccess > 0) return false;
if (isReading(thread)) return true; //读重入,放在写请求判断前,确保优先级比它高
if (writeRequests > 0) return false;
return true;
}
private boolean isReading(Thread thread) {
return readingThreads.get(thread) != null;
}
private int getReadAccessCount(Thread thread) {
Integer count = readingThreads.get(thread);
if (count == null) return 0;
return count;
}
//-----------------------写------------------------------------
public synchronized void lockWrite() throws InterruptedException {
writeRequests++;
Thread callingThread = Thread.currentThread();
while (!canGetWriteAccess(callingThread)) {
wait();
}
writeRequests--;
writeAccess++;
writingThread = callingThread;
}
public synchronized void unlockWrite() {
if (!isWriting(Thread.currentThread())) {
throw new IllegalMonitorStateException("当前线程没有持有该对象的写锁");
}
writeAccess--;
if (writeAccess == 0) {
writingThread = null;
}
notifyAll();
}
private boolean canGetWriteAccess(Thread callingThread) {
if (isOnlyReader(callingThread)) return true; //读写重入
if (hasReader()) return false;
if (writingThread == null) return true;
if (isWriting(callingThread)) return true;
return false;
}
private boolean isWriting(Thread callingThread) {
return callingThread == writingThread;
}
private boolean hasReader() {
return readingThreads.size() > 0;
}
private boolean isOnlyReader(Thread callingThread) {
return readingThreads.size() == 1 &&
readingThreads.get(callingThread) != null;
}
}