Skip to content

Commit b7b3f1a

Browse files
authored
fix: correct volatile description for AQS state variable (issue #2516) (#2829)
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 #2516
1 parent 38f77e3 commit b7b3f1a

File tree

1 file changed

+2
-2
lines changed

1 file changed

+2
-2
lines changed

docs/java/concurrent/aqs.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -106,10 +106,10 @@ AQS(`AbstractQueuedSynchronizer`)的核心原理图:
106106

107107
AQS 使用 **int 成员变量 `state` 表示同步状态**,通过内置的 **FIFO 线程等待/等待队列** 来完成获取资源线程的排队工作。
108108

109-
`state` 变量由 `volatile` 修饰,用于展示当前临界资源的获取情况。
109+
`state` 变量由 `volatile` 修饰,用于展示当前临界资源的获取情况。这里 `volatile` 的作用不仅仅是保证可见性,更重要的是通过 happens-before 规则(volatile 变量的写操作先行发生于后续的读操作)防止编译器和处理器对指令进行重排序,从而保证锁语义的正确性。
110110

111111
```java
112-
// 共享变量,使用volatile修饰保证线程可见性
112+
// 共享变量,使用volatile修饰,保证线程可见性并防止指令重排序
113113
private volatile int state;
114114
```
115115

0 commit comments

Comments
 (0)