ReentrantLock的内存可见性语义
Nadie ha tomado este issue todavía.
Evaluación
- Dificultad
- 4/5
- Tiempo estimado
- 3-5 días
- Aptitud para principiantes
- 35/100
- Tipo de issue
- Documentación
- Claridad
- Necesita aclaración
- Estado de actividad
- Estancado
- Stack tecnológico
- java, linux
Línea de trabajo
Start with ReentrantLock's NonfairSync.lock, AbstractQueuedSynchronizer.compareAndSetState, setState, and tryRelease, then compare their documented volatile memory semantics with the referenced JSR-133 Cookbook. Review the Linux Atomic::cmpxchg implementation and x86 lock-prefixed instruction discussion. Done means documenting the acquire and release ordering clearly, including what is guaranteed by Java rather than by x86 alone.
Escrito por el modelo de indexación a partir del texto del issue.
Descripción
加锁
以NonfairSync为例:
final void lock() {
if (compareAndSetState(0, 1))
setExclusiveOwnerThread(Thread.currentThread());
else
acquire(1);
}
关键在于compareAndSetState方法:
/**
* Atomically sets synchronization state to the given updated
* value if the current state value equals the expected value.
* This operation has memory semantics of a {@code volatile} read
* and write.
*
* @param expect the expected value
* @param update the new value
* @return {@code true} if successful. False return indicates that the actual
* value was not equal to the expected value.
*/
protected final boolean compareAndSetState(int expect, int update) {
return unsafe.compareAndSwapInt(this, stateOffset, expect, update);
}
注释里写了,此方法有相当于volatile读写的内存语义。所以这个内存语义又是什么?
参考Doug lea的: The JSR-133 Cookbook for Compiler Writers
- Issue a StoreStore barrier before each volatile store
- Issue a StoreLoad barrier after each volatile store.(Alternatively, if available, you can implement volatile store as an atomic instruction (for example XCHG on x86) and omit the barrier. This may be more efficient if atomic instructions are cheaper than StoreLoad barriers.)
- Issue LoadLoad and LoadStore barriers after each volatile load.
unsafe.compareAndSwapInt由Atomic::cmpxchg实现(Linux):
inline jlong Atomic::cmpxchg (jlong exchange_value, volatile jlong* dest, jlong compare_value) {
bool mp = os::is_MP();
__asm__ __volatile__ (LOCK_IF_MP(%4) "cmpxchgq %1,(%3)"
: "=a" (exchange_value)
: "r" (exchange_value), "a" (compare_value), "r" (dest), "r" (mp)
: "cc", "memory");
return exchange_value;
}
所以这在x86上就是加了lock前缀的cmpxhgg指令,而lock前缀在intel上便充当了读写memory barrier的作用,来自书中的摘抄L:
On the other hand, x86 CPUs have traditionally given no ordering guarantees for loads, so the smp_mb() and smp_rmb() primitives expand to lock;addl. This atomic instruction acts as a barrier to both loads and stores.
解锁
只看一行:
protected final boolean tryRelease(int releases) {
// ...
setState(c);
// ...
}
/**
* Sets the value of synchronization state.
* This operation has memory semantics of a {@code volatile} write.
* @param newState the new state value
*/
protected final void setState(int newState) {
state = newState;
}
从前面Doug lea的文章中可以看出,volatile写会导致在后面追加一个StoreLoad屏障,而此屏障在x86上:

So,也许又是一条lock前缀指令。
- Lenguaje dominante
- Java
- Estrellas
- 2k
- Forks
- 716
- Métricas de merge de PR
- Sin PR fusionados en 30 d
Preparar el entorno
Este proyecto no incluye contenedor de desarrollo, Dockerfile ni guía de contribución, así que la configuración corre por tu cuenta: empieza por su README y consulta nuestra guía para la primera contribución para los pasos generales.
Primeros pasos
- Lee el issue completo y luego la guía de contribución del proyecto.
- Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
- Haz un fork del repositorio y trabaja en una rama.
- Abre un pull request que haga referencia al número del issue.
Más de seaswalker/jdk-sourcecode-analysis
-
一种从值转为枚举的方法Abierto
Dificultad 2/5 1-3 horas Aptitud para principiantes 35/100
-
求一个HttpConnectionSocketImpl的源码分析Abierto
Dificultad 4/5 3-5 días Aptitud para principiantes 20/100
-
JMM和Linux内存屏障定义Abierto
Dificultad 5/5 Más de una semana Aptitud para principiantes 25/100
-
令人迷惑的volatile例子(三)Abierto
Dificultad 5/5 Más de una semana Aptitud para principiantes 18/100
-
令人迷惑的volatile例子(二)Abierto
Dificultad 5/5 Más de una semana Aptitud para principiantes 25/100
Todos los issues de seaswalker/jdk-sourcecode-analysis
Issues similares
-
[Bug] The producer summary counts an unreported client version as a second version and warns about a version mixPosiblemente ocupada Un pull request vinculado a esta issue está abierto o ya se fusionó. Abierto
Dificultad 2/5 1-3 horas Aptitud para principiantes 74/100
apache/rocketmq-dashboard#6110 ·
Los mantenedores suelen responder en 4 días
-
`Processing lsp` never exits and leaves orphaned processesPosiblemente ocupada @overcast302 la tomó hoy. Abiertobug
Dificultad 2/5 1-3 horas Aptitud para principiantes 72/100
processing/processing4#1578 · 1 comentario ·
-
Dificultad 2/5 1-3 horas Aptitud para principiantes 72/100
apache/doris-flink-connector#707 ·
-
ASM is not up-to-dateAbierto
Dificultad 2/5 1-3 horas Aptitud para principiantes 60/100
Los mantenedores suelen responder en 1 día
-
[BUG] S3 CORS responses omit Access-Control-Allow-Credentials for matched originsPosiblemente ocupada Un pull request vinculado a esta issue está abierto o ya se fusionó. Abierto
Dificultad 2/5 1-3 horas Aptitud para principiantes 72/100
floci-io/floci#5369 · 1 comentario ·
Los mantenedores suelen responder en 1 día