Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does a Java Lock object enforce a happens-before relationship?

Java provides a Lock object in the concurrency package that according to the documentation provides more extensive locking operations than can be obtained using synchronized methods and statements.

The synchronized methods/blocks besides mutual exclusion, enforce a happens-before relationship which makes sure that changed made to the variable by one thread are visible to the other.

Does this relationship occur when using a Lock object? Is observation guaranteed like in the case of synchronized block for all platforms?

like image 990
Petrakeas Avatar asked Sep 30 '15 10:09

Petrakeas


2 Answers

Yes, it does.

Lock objects work very much like the implicit locks used by synchronized code. As with implicit locks, only one thread can own a Lock object at a time. Lock objects also support a wait/notify mechanism, through their associated Condition objects.

From https://docs.oracle.com/javase/tutorial/essential/concurrency/newlocks.html

like image 138
Andres Avatar answered Sep 16 '22 11:09

Andres


Does this relationship occur when using a Lock object? Is observation guaranteed like in the case of synchronized block for all platforms?

Yes, it does.

There are several actions that create happens-before relationships and one of them is synchronization (here), and Java's lock object is also meant for that purpose.

Read about Java's Memory Consistency Properties from Oracle docs. Except below which will be highlight in the link.

In below "extend these guarantees" means memory consistency properties like "happens-before" relationships. Lock class belongs to subpackage of java.util.concurrent, so it guarantees memory consistency properties like "happens-before" relationships and more.

The methods of all classes in java.util.concurrent and its subpackages extend these guarantees to higher-level synchronization.

like image 34
hagrawal Avatar answered Sep 16 '22 11:09

hagrawal