Franz Kafka
Franz Kafka

Reputation: 10841

Java lock and happend-before relation

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?

Upvotes: 1

Views: 145

Answers (3)

Joonas Pulakka
Joonas Pulakka

Reputation: 36577

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.

Upvotes: 2

JB Nizet
JB Nizet

Reputation: 691865

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.

Upvotes: 4

Brian Roach
Brian Roach

Reputation: 76908

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.

The relevant Oracle tutorial can be found here.

Upvotes: 2

Related Questions