| FazBrowse GitHub Viewer | Trending | | Home |
| Tools: [Download Repo ZIP] [Original HTTPS Page] |
…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
| Back | FazBrowse Home | New Git URL |
修复 AQS 中 state 变量的 volatile 作用描述不准确问题
问题描述
关闭 #2516
原文中代码注释为:
以及描述文字仅提到 volatile 用于"展示当前临界资源的获取情况"。
问题分析
volatile 在 AQS state 变量中的作用不仅仅是保证可见性。实际上,在 AQS 实现中更关键的是通过 happens-before 规则来防止指令重排序:
这保证了锁的获取/释放操作的语义正确性——即线程释放锁(写 state)之后,另一个线程获取锁(读 state)能看到所有在释放锁之前的操作。
修改内容