fix: correct volatile description for AQS state variable#2829
Merged
Snailclimb merged 1 commit intoSnailclimb:mainfrom Apr 15, 2026
Merged
Conversation
…climb#2516) The previous description only mentioned thread visibility as the reason for using volatile to modify the state variable. However, volatile's more important role here is preventing instruction reordering through the happens-before rule (volatile write happens-before subsequent read), which ensures the correctness of lock semantics. Fixes Snailclimb#2516
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
修复 AQS 中
state变量的volatile作用描述不准确问题问题描述
关闭 #2516
原文中代码注释为:
以及描述文字仅提到
volatile用于"展示当前临界资源的获取情况"。问题分析
volatile在 AQSstate变量中的作用不仅仅是保证可见性。实际上,在 AQS 实现中更关键的是通过 happens-before 规则来防止指令重排序:这保证了锁的获取/释放操作的语义正确性——即线程释放锁(写
state)之后,另一个线程获取锁(读state)能看到所有在释放锁之前的操作。修改内容
// 共享变量,使用volatile修饰,保证线程可见性并防止指令重排序