Java 读写锁原理详解:从基础实现到可重入机制完整指南
时间:2026-11-11 | 作者:半糖攻略君 | 阅读:0尽管 Java 5 在 java.util.concurrent 包中已经内置了成熟的读写锁工具,但理解其底层的实现逻辑对于掌握并发编程依然至关重要。这有助于我们在面对复杂场景时,能够更清晰地判断锁的行为与性能表现。
资源免费获取入口夸克直达:☜☜☜☜☜点击进入
- Java 读写锁的核心实现逻辑
- 读写锁的可重入性机制
- 读锁的重入处理
- 写锁的重入处理
- 读锁向写锁的升级策略
- 写锁向读锁的降级策略
- 构建完全可重入的 ReadWriteLock
- 在 finally 块中安全释放锁资源
读写锁的基础实现思路
在进行资源访问之前,我们需要明确读取和写入操作所依赖的前提条件:
读取操作:当前必须没有线程正在进行写操作,同时也不能有其他线程正在排队请求写操作。
写入操作:当前必须没有任何线程持有读锁或写锁,即资源处于完全空闲状态。
当某个线程试图获取读锁时,只要确认没有线程在执行写操作,且没有其他线程在等待写权限,该线程即可进入。这里有一个重要的设计权衡:如果我们将写操作的优先级调高,可以有效避免“写饥饿”现象。所谓写饥饿,是指如果系统持续允许新的读线程进入,而让等待写的线程一直阻塞,最终导致写操作永远无法执行。因此,标准的实现通常会在有写请求排队时,暂停新的读请求,直到当前的写操作完成。
对于写锁而言,只有当共享资源未被任何线程(无论是读还是写)占用时,请求写锁的线程才能获得权限。至于有多少个线程在排队申请写锁,或者它们申请的顺序如何,除非我们特意实现了公平锁算法,否则默认情况下并不保证严格的 FIFO 顺序。
基于上述逻辑,我们可以先构建一个基础的读写锁框架,代码如下:
public class ReadWriteLock{
private int readers = 0;
private int writers = 0;
private int writeRequests = 0;
public synchronized void lockRead()
throws InterruptedException{
while(writers > 0 || writeRequests > 0){
wait();
}
readers++;
}
public synchronized void unlockRead(){
readers--;
notifyAll();
}
public synchronized void lockWrite()
throws InterruptedException{
writeRequests++;
while(readers > 0 || writers > 0){
wait();
}
writeRequests--;
writers++;
}
public synchronized void unlockWrite()
throws InterruptedException{
writers--;
notifyAll();
}
}
在这个基础的 ReadWriteLock 类中,分别定义了获取和释放读锁、写锁的独立方法。
读锁的获取逻辑位于 lockRead() 方法内。只要检测到 writers 为 0(无写锁持有者)且 writeRequests 为 0(无写请求排队),任何线程都可以成功获取读锁。
写锁的获取逻辑位于 lockWrite() 方法内。线程首先将 writeRequests 计数器加 1,表示发起请求。随后检查是否满足获取条件:即 readers 为 0 且 writers 为 0。一旦满足,writeRequests 减 1,writers 加 1,正式获得写锁。此过程中,排队中的其他写线程数量不影响当前线程的判断逻辑。
在释放锁的方法 unlockRead 和 unlockWrite 中,关键区别在于使用了 notifyAll() 而非 notify()。这一选择是为了防止信号丢失导致的死锁风险。
假设场景中既有等待读锁的线程,也有等待写锁的线程。如果使用 notify(),系统可能随机唤醒一个等待读锁的线程。但由于此时仍有 writeRequests > 0,该读线程会立即再次进入等待状态。与此同时,真正应该被唤醒的写锁线程却未被通知,导致信号中断,所有线程继续僵持。使用 notifyAll() 可以确保所有等待线程都被唤醒并重新评估自身状态,从而打破僵局。
此外,notifyAll() 还能提升并发效率。例如,当多个读线程在等待,且没有写请求时,一旦写锁被释放,调用 notifyAll() 会让所有等待的读线程同时尝试获取锁,虽然最终只有一个能成功,但这种批量唤醒机制比逐个唤醒更符合多读场景的性能预期。
读写锁的重入问题
前文实现的 ReadWriteLock 是不可重入的。这意味着,如果一个线程已经持有了写锁,它再次尝试获取写锁时,会因为检测到 writers > 0(即自己持有的锁)而陷入无限等待。同样地,考虑以下死锁场景:
- 线程 A 成功获取了读锁。
- 线程 B 尝试获取写锁,但因线程 A 持有读锁而被阻塞。
- 此时,线程 A 尝试再次获取读锁。由于存在 pending 的写请求(线程 B),根据之前的逻辑,线程 A 也会被阻塞。结果就是线程 A 和线程 B 互相等待,形成死锁,系统将无法继续推进。
为了解决这个问题,我们需要对 ReadWriteLock 进行改进,使其支持重入。下面将分别阐述读锁和写锁的重入实现方案。
读锁重入机制
要实现读锁重入,需确立以下规则:
若线程已持有读锁,无论是否有写请求排队,都应允许其再次获取读锁;若未持有,则需满足常规获取条件(无写锁且无写请求)。为此,我们引入一个 Map 结构来记录每个线程持有的读锁次数。以下是修改后的 lockRead 和 unlockRead 代码:
public class ReadWriteLock{
private Map<Thread, Integer> readingThreads =
new HashMap<Thread, Integer>();
private int writers = 0;
private int writeRequests = 0;
public synchronized void lockRead()
throws InterruptedException{
Thread callingThread = Thread.currentThread();
while(! canGrantReadAccess(callingThread)){
wait();
}
readingThreads.put(callingThread,
(getAccessCount(callingThread) + 1));
}
public synchronized void unlockRead(){
Thread callingThread = Thread.currentThread();
int accessCount = getAccessCount(callingThread);
if(accessCount == 1) {
readingThreads.remove(callingThread);
} else {
readingThreads.put(callingThread, (accessCount -1));
}
notifyAll();
}
private boolean canGrantReadAccess(Thread callingThread){
if(writers > 0) return false;
if(isReader(callingThread) return true;
if(writeRequests > 0) return false;
return true;
}
private int getReadAccessCount(Thread callingThread){
Integer accessCount = readingThreads.get(callingThread);
if(accessCount == null) return 0;
return accessCount.intValue();
}
private boolean isReader(Thread callingThread){
return readingThreads.get(callingThread) != null;
}
}
通过上述代码可见,只有当没有写锁持有者时,才允许新的读锁获取。同时,已持有读锁的线程拥有更高的优先级,即使存在写请求,也能顺利重入,这体现了读优先的策略。
写锁重入机制
写锁的重入更为严格:仅当线程已经持有写锁时,才允许其再次获取写锁。以下是修改后的 lockWrite 和 unlockWrite 代码:
public class ReadWriteLock{
private Map<Thread, Integer> readingThreads =
new HashMap<Thread, Integer>();
private int writeAccesses = 0;
private int writeRequests = 0;
private Thread writingThread = null;
public synchronized void lockWrite()
throws InterruptedException{
writeRequests++;
Thread callingThread = Thread.currentThread();
while(!canGrantWriteAccess(callingThread)){
wait();
}
writeRequests--;
writeAccesses++;
writingThread = callingThread;
}
public synchronized void unlockWrite()
throws InterruptedException{
writeAccesses--;
if(writeAccesses == 0){
writingThread = null;
}
notifyAll();
}
private boolean canGrantWriteAccess(Thread callingThread){
if(hasReaders()) return false;
if(writingThread == null) return true;
if(!isWriter(callingThread)) return false;
return true;
}
private boolean hasReaders(){
return readingThreads.size() > 0;
}
private boolean isWriter(Thread callingThread){
return writingThread == callingThread;
}
}
注意 canGrantWriteAccess 方法的判断逻辑:首先检查是否有读者(若有则拒绝),其次检查当前写锁持有者是否为空(若为空则允许新写者),最后检查当前请求者是否为已有写者(若是则允许重入)。
读锁升级为写锁
在某些业务场景下,希望持有读锁的线程能直接升级为写锁。这需要满足一个前提:该线程必须是当前唯一的读锁持有者。为了实现这一点,我们需要调整 canGrantWriteAccess 的逻辑:
public class ReadWriteLock{
private Map<Thread, Integer> readingThreads =
new HashMap<Thread, Integer>();
private int writeAccesses = 0;
private int writeRequests = 0;
private Thread writingThread = null;
public synchronized void lockWrite()
throws InterruptedException{
writeRequests++;
Thread callingThread = Thread.currentThread();
while(!canGrantWriteAccess(callingThread)){
wait();
}
writeRequests--;
writeAccesses++;
writingThread = callingThread;
}
public synchronized void unlockWrite() throws InterruptedException{
writeAccesses--;
if(writeAccesses == 0){
writingThread = null;
}
notifyAll();
}
private boolean canGrantWriteAccess(Thread callingThread){
if(isOnlyReader(callingThread)) return true;
if(hasReaders()) return false;
if(writingThread == null) return true;
if(!isWriter(callingThread)) return false;
return true;
}
private boolean hasReaders(){
return readingThreads.size() > 0;
}
private boolean isWriter(Thread callingThread){
return writingThread == callingThread;
}
private boolean isOnlyReader(Thread thread){
return readers == 1 && readingThreads.get(callingThread) != null;
}
}
经过上述改造,ReadWriteLock 现在支持从读锁到写锁的升级。当且仅当调用线程是唯一的读者时,它才能获取写锁。
写锁降级为读锁
反之,持有写锁的线程也可以轻松获取读锁。因为一旦拥有写锁,就意味着没有其他线程在读或写,所以此时获取读锁不会引发竞争或数据不一致。我们只需简单修改 canGrantReadAccess 方法即可:
public class ReadWriteLock{
private boolean canGrantReadAccess(Thread callingThread){
if(isWriter(callingThread)) return true;
if(writingThread != null) return false;
if(isReader(callingThread) return true;
if(writeRequests > 0) return false;
return true;
}
}
完全可重入的 ReadWriteLock 整合实现
下面是整合了上述所有特性的完整 ReadWriteLock 实现。为了代码的整洁性和可读性,我们对之前的片段进行了重构和整理。
public class ReadWriteLock{
private Map<Thread, Integer> readingThreads =
new HashMap<Thread, Integer>();
private int writeAccesses = 0;
private int writeRequests = 0;
private Thread writingThread = null;
public synchronized void lockRead()
throws InterruptedException{
Thread callingThread = Thread.currentThread();
while(! canGrantReadAccess(callingThread)){
wait();
}
readingThreads.put(callingThread,
(getReadAccessCount(callingThread) + 1));
}
private boolean canGrantReadAccess(Thread callingThread){
if(isWriter(callingThread)) return true;
if(hasWriter()) return false;
if(isReader(callingThread)) return true;
if(hasWriteRequests()) return false;
return true;
}
public synchronized void unlockRead(){
Thread callingThread = Thread.currentThread();
if(!isReader(callingThread)){
throw new IllegalMonitorStateException(
"Calling Thread does not" +
" hold a read lock on this ReadWriteLock");
}
int accessCount = getReadAccessCount(callingThread);
if(accessCount == 1){
readingThreads.remove(callingThread);
} else {
readingThreads.put(callingThread, (accessCount -1));
}
notifyAll();
}
public synchronized void lockWrite()
throws InterruptedException{
writeRequests++;
Thread callingThread = Thread.currentThread();
while(!canGrantWriteAccess(callingThread)){
wait();
}
writeRequests--;
writeAccesses++;
writingThread = callingThread;
}
public synchronized void unlockWrite()
throws InterruptedException{
if(!isWriter(Thread.currentThread()){
throw new IllegalMonitorStateException(
"Calling Thread does not" +
" hold the write lock on this ReadWriteLock");
}
writeAccesses--;
if(writeAccesses == 0){
writingThread = null;
}
notifyAll();
}
private boolean canGrantWriteAccess(Thread callingThread){
if(isOnlyReader(callingThread)) return true;
if(hasReaders()) return false;
if(writingThread == null) return true;
if(!isWriter(callingThread)) return false;
return true;
}
private int getReadAccessCount(Thread callingThread){
Integer accessCount = readingThreads.get(callingThread);
if(accessCount == null) return 0;
return accessCount.intValue();
}
private boolean hasReaders(){
return readingThreads.size() > 0;
}
private boolean isReader(Thread callingThread){
return readingThreads.get(callingThread) != null;
}
private boolean isOnlyReader(Thread callingThread){
return readingThreads.size() == 1 &&
readingThreads.get(callingThread) != null;
}
private boolean hasWriter(){
return writingThread != null;
}
private boolean isWriter(Thread callingThread){
return writingThread == callingThread;
}
private boolean hasWriteRequests(){
return this.writeRequests > 0;
}
}
务必在 finally 块中调用 unlock()
在使用 ReadWriteLock 保护临界区代码时,如果临界区内可能发生异常,必须在 finally 块中显式调用 unlockRead() 或 unlockWrite()。这是为了确保无论发生什么,锁都能被正确释放,从而避免其他线程永久阻塞。
lock.lockWrite();
try{
//执行可能抛出异常的临界区代码
} finally {
lock.unlockWrite();
}
这种 try-finally 结构是 Java 并发编程的最佳实践。如果 unlockWrite 不在 finally 中,一旦临界区抛出异常,写锁将永远不会被释放,导致所有后续尝试获取读锁或写锁的线程全部挂起。虽然如果锁是可重入的,当前线程可能在捕获异常后重新获取锁并解锁,但这依赖于特定的代码路径,并非可靠保障。因此,养成在 finally 中释放锁的习惯,是编写健壮并发代码的关键。
以上就是关于 Java 多线程读写锁原理的详细解析。通过理解这些底层机制,开发者可以更好地利用并发工具优化程序性能。请注意,实际生产环境中建议优先使用 java.util.concurrent 包提供的标准实现,以确保安全性和稳定性。
免责声明:文中图文均来自网络,如有侵权请联系删除,心愿游戏发布此文仅为传递信息,不代表心愿游戏认同其观点或证实其描述。
相关文章
更多-
- Java多线程ExecutorService实战:核心接口解析与线程池使用指南
- 时间:2026-11-11
-
- Java集合工具:TreeMap与TreeSet自定义排序实现指南
- 时间:2026-11-11
-
- Java中Vector与ArrayList源码深度对比:线程安全与扩容机制解析
- 时间:2026-11-11
-
- Java XML转换空指针异常排查:DOM节点为空导致Transformer报错的解决思路
- 时间:2026-11-11
-
- Java 8 四大内置函数式接口详解与代码示例
- 时间:2026-11-11
-
- Java定时任务基础:Timer与TimerTask简单示例与安全使用指南
- 时间:2026-11-11
-
- Java核心机制与安全编程指南:从反射到并发控制
- 时间:2026-11-11
-
- Java开发基础:理清Collection接口与Collections工具类的核心差异
- 时间:2026-11-11
精选合集
更多大家都在玩
热门话题
大家都在看
更多-
- 耀阳逐光,闪烁贺典!《闪烁之光》7.5周年庆典重磅开启,全新UR「羲和」上线,万抽福利免费送!
- 时间:2026-11-26
-
- 《花开时见你》正式开启预约!花开时,遇见更美的你,治愈系魔法花店即将营业!
- 时间:2026-11-26
-
- 正版授权全新沙盒体验!饥荒正版《饥困荒野》手游今日上线
- 时间:2026-11-24
-
- C#处理XML文件指南:XmlDocument与Linq操作详解及避坑
- 时间:2026-11-11
-
- Java多线程ExecutorService实战:核心接口解析与线程池使用指南
- 时间:2026-11-11
-
- Laravel全局函数配置指南:从助手类到自定义加载的完整教程
- 时间:2026-11-11
-
- C# 数组去重教程:对比两个列表并提取差异元素
- 时间:2026-11-11
-
- PHP引用符号&详解:变量、函数与对象操作指南
- 时间:2026-11-11