作者归档

Java锁是如何保证数据可见性的

引言

java.util.concurrent.locks.Lock 接口的Javadoc中有这样一段话:

All Lock implementations must enforce the same memory synchronization semantics as provided by the built-in monitor lock :

  • A successful lock operation acts like a successful monitorEnter action
  • A successful unlock operation acts like a successful monitorExit action

Unsuccessful locking and unlocking operations, and reentrant locking/unlocking operations, do not require any memory synchronization effects.

这段话的核心是j.u.c.locks.Lock接口的实现类具有和synchronized内置锁一样的内存同步语义。

不同于由JVM底层实现的内置锁,Lock接口的实现类是直接用Java代码实现的。如何保证了内存中数据的可见性?下面进行一下分析。

阅读全文

return top