# 04-锁内存语义的实现

锁一般式基于AQS实现的，AQS维护了一个volatile的state， 这个state式实现锁内存语义的关键

## CAS

如果当前状态值等于预期值，则以原子方式将同步状态设置为给定的更新值。此操作具有volatile读和写的内存语义。

编译器不会对volatile读与volatile读后面的任意内存操作重排序；编译器不会对volatile写与volatile写前面的任意内存操作重排序。组合这两个条件，意味着为了同时实现volatile读和volatile写的内存语义，编译器不能对CAS与CAS前面和后面的任意内存操作重排序

## 内存语义总结

* 公平锁和非公平锁释放时，最后都要写一个volatile变量state。
* 公平锁获取时，首先会去读volatile变量。
* 非公平锁获取时，首先会用CAS更新volatile变量，这个操作同时具有volatile读和volatile写的内存语义。


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://yibingxiong.gitbook.io/java-concurrent-programming-art-mini/di-09-zhang-java-nei-cun-mo-xing/04-suo-nei-cun-yu-yi-de-shi-xian.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
