Locks are one of the basic synchronization mechanisms provided by the Java Concurrency API. They allow programmers to protect a critical section of code so only one thread can execute that block of code at a time. It provides the following two operations:
- lock(): You call this operation when you want to access a critical section. If there is another thread running this critical section, other threads are blocked until they're woken up by the lock to get access to the critical section.
- unlock(): You call this operation at the end of a critical section to allow other threads to access it.
In the Java Concurrency API, locks are declared in the Lock interface and implemented in some classes, for example, the ReentrantLock class.
In this recipe, you will learn how to implement your own Lock object by implementing a class that implements the Lock interface, which can be used to...