Java FencedLock

Table of Contents

Java FencedLock

https://redisson.pro/glossary/java-fencedlock.html

In computer science, a lock is a synchronization mechanism that only allows a single thread access to a shared resource simultaneously. This prevents multiple threads from accessing the same resource simultaneously, which can cause race conditions and other issues and errors.

The Java programming language helps software developers perform locking via concepts such as the FencedLock. The FencedLock data structure is a distributed lock that implements the java.util.concurrent.locks.Lock interface with well-defined behavior during execution and failure.

Distributed locking is even more complicated than standard locking, which is typically concerned only with threads on a single machine. In distributed locking, different clients on separate machines may attempt to access the same resource, such as a file or database. Distributed systems need to handle problems such as partial failure, in which some system components are down while others continue operating.

The FencedLock works by using a fencing token: a number that is increased each time a client acquires the lock. The client needs to pass this token to any external services and include the token in every request. If a service has received requests with two different tokens, it accepts the request with the highest token number and rejects all other requests. This ensures that even if two clients have the lock simultaneously, the external service can only interact with one client simultaneously.

Any critical section in the code protected by a FencedLock is guaranteed to be executed by only one thread in the cluster. However, the FencedLock does not provide fairness. I.e., it cannot ensure that different threads or processes can equitably share access to the resource. The FencedLock provides consistency and partition tolerance but does not provide availability, which makes it a CP concept according to the CAP theorem.