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
synchronized
keyword, you only have control over a synchronized block of code in a structured way. However, theLock
interface allows you to get more complex structures to implement your critical section. - The
Lock
interface provides additional functionalities over thesynchronized
keyword. 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 thesynchronized
keyword, if thread (A) tries to execute a synchronized...