Java lock and happend-before relation
-
16-02-2021 - |
Вопрос
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?
Решение
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.
Другие советы
It's ... a (mutex) lock:
void myMethod()
{
myLock.lock(); // block until condition holds
try
{
// Do stuff that only one thread at a time should do
}
finally
{
myLock.unlock()
}
}
Only one thread can hold the lock at a time, so anything between the lock()
and unlock()
calls is guaranteed to only be executed by one thread at a time.
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 a synchronized
block.
The existence ReentrantLock
is justified by that it provides more flexibility than synchronized
: you can, for example, just try to acquire the lock - not possible with synchronized
.