Synchronizing a block of code with a lock
Java provides another mechanism for synchronizing blocks of code. It's a more powerful and flexible mechanism than the synchronized keyword. It's based on the Lock (of the java.util.concurrent.locks package) interface and classes that implement it (as ReentrantLock). This mechanism presents some advantages, which are as follows:
- It allows you to structure synchronized blocks in a more flexible way. With the
synchronizedkeyword, you only have control over a synchronized block of code in a structured way. However, theLockinterface allows you to get more complex structures to implement your critical section. - The
Lockinterface provides additional functionalities over thesynchronizedkeyword. One of the new functionalities is implemented by thetryLock()method. This method tries to get control of the lock, and if it can't, because it's used by another thread, it returnsfalse. With thesynchronizedkeyword, if thread (A) tries to execute a synchronized...