Skip to content

fix: correct volatile description for AQS state variable#2829

Merged
Snailclimb merged 1 commit intoSnailclimb:mainfrom
Senrian:fix/aqs-state-volatile-explanation-2516
Apr 15, 2026
Merged

fix: correct volatile description for AQS state variable#2829
Snailclimb merged 1 commit intoSnailclimb:mainfrom
Senrian:fix/aqs-state-volatile-explanation-2516

Conversation

@Senrian
Copy link
Copy Markdown
Contributor

@Senrian Senrian commented Apr 14, 2026

修复 AQS 中 state 变量的 volatile 作用描述不准确问题

问题描述

关闭 #2516

原文中代码注释为:

// 共享变量,使用volatile修饰保证线程可见性
private volatile int state;

以及描述文字仅提到 volatile 用于"展示当前临界资源的获取情况"。

问题分析

volatile 在 AQS state 变量中的作用不仅仅是保证可见性。实际上,在 AQS 实现中更关键的是通过 happens-before 规则来防止指令重排序:

JMM 的 happens-before 规则规定:volatile 变量的写操作先行发生于后续的读操作。

这保证了锁的获取/释放操作的语义正确性——即线程释放锁(写 state)之后,另一个线程获取锁(读 state)能看到所有在释放锁之前的操作。

修改内容

  1. 更新代码注释:// 共享变量,使用volatile修饰,保证线程可见性并防止指令重排序
  2. 在描述文字中补充 happens-before 规则的解释

…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
@Snailclimb Snailclimb merged commit b7b3f1a into Snailclimb:main Apr 15, 2026
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants