Java锁和发生前关系
我不确定我是否正确解释了 javadoc。在调用 lock
方法并成功获得锁后使用 ReentrantLock
时,您是否可以在没有任何同步块的情况下访问任何对象,并且发生之前的关系会神奇地强制执行?
我没有看到 ReentrantLock 和我正在处理的对象之间有任何联系,这就是为什么很难相信我可以安全地处理它们。但事实就是如此,还是我读的javadoc错了?
I'm not sure if I'm interpreting the javadoc right. When using a ReentrantLock
after calling the lock
method and successfully gaining a lock, can you just access any object without any synchronized blocks and the happend-before relationship is magically enforced?
I don't see any connection between the ReentrantLock
and the objects I'm working on, that's why it is hard to believe I can work on them safely. But this is the case, or am I reading the javadoc wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果线程 A 修改了由锁保护的代码块 CB1 内的某个对象,然后释放锁,并且线程 B 进入由同一锁保护的代码块中,则线程 B 将在代码中看到线程 A 所做的修改块 CB1。
如果两个线程读取和写入相同的共享状态,则对该状态的每次读取和写入都应该由相同的锁来保护。
If thread A has modified some object inside a code block CB1 guarded by the lock and then releases the lock, and thread B enters in a code block guarded by the same lock, then thread B will see the modifications done by thread A in the code block CB1.
If two threads read and write the same shared state, then every read and write to this state should be guarded by the same lock.
它是......(互斥)锁:
一次只有一个线程可以持有锁,因此
lock()
和unlock()
调用之间的任何操作都保证一次只能由一个线程执行。可以在此处找到相关的 Oracle 教程。
It's ... a (mutex) lock:
Only one thread can hold the lock at a time, so anything between the
lock()
andunlock()
calls is guaranteed to only be executed by one thread at a time.The relevant Oracle tutorial can be found here.
这里面没有魔法。当且仅当访问某个对象的所有线程都使用相同的锁时(无论是 ReentrantLock 还是任何其他互斥锁,例如 Synchronized 块),您才是安全的。
ReentrantLock
的存在是合理的,因为它比synchronized
提供了更多的灵活性:例如,您可以尝试获取锁 - 不可能与同步
。There's no magic in it. You're safe if, and only if, all threads accessing an object use the same lock - be it a
ReentrantLock
or any other mutex, such as asynchronized
block.The existence
ReentrantLock
is justified by that it provides more flexibility thansynchronized
: you can, for example, just try to acquire the lock - not possible withsynchronized
.