Reputation: 1690
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?
Upvotes: 7
Views: 612
Reputation: 14668
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.
Upvotes: 2
Reputation: 10717
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
Upvotes: 3