The lockable object design pattern ensures that there is only one user using the target object. Compared to the built-in synchronization mechanisms such as using the `synchronized` keyword, this pattern can lock objects for an undetermined time and is not tied to the duration of the request.
The Lockable Object pattern aims to control access to a shared resource in a multithreaded environment by providing a mechanism for resource locking, ensuring that only one thread can access the resource at a time.
## Explanation
Real world example
Real-world example
> Imagine a shared printer in a busy office as an analogous real-world example of the Lockable Object design pattern. Multiple employees need to print documents throughout the day, but the printer can only handle one print job at a time. To manage this, there's a locking system in place—much like a lockable object in programming—that ensures when one person is printing, others must wait their turn. This prevents print jobs from overlapping or interfering with each other, ensuring that each document is printed correctly and in the order it was sent, mirroring the concept of thread synchronization and resource locking in software development.
>The Sword Of Aragorn is a legendary object that only one creature can possess at the time.
>Every creature in the middle earth wants to possess is, so as long as it's not locked, every creature will fight for it.
In plain words
Under the hood
>In this particular module, the SwordOfAragorn.java is a class that implements the Lockable interface.
It reaches the goal of the Lockable-Object pattern by implementing unlock() and unlock() methods using
thread-safety logic. The thread-safety logic is implemented with the built-in monitor mechanism of Java.
The SwordOfAaragorn.java has an Object property called "synchronizer". In every crucial concurrency code block,
it's synchronizing the block by using the synchronizer.
> The Lockable Object design pattern ensures safe access to a shared resource in a multithreaded environment by allowing only one thread to access the resource at a time through locking mechanisms.
Wikipedia says
> In computer science, a lock or mutex (from mutual exclusion) is a synchronization primitive that prevents state from being modified or accessed by multiple threads of execution at once. Locks enforce mutual exclusion concurrency control policies, and with a variety of possible methods there exist multiple unique implementations for different applications.
**Programmatic Example**
The Lockable Object pattern is a concurrency pattern that allows only one thread to access a shared resource at a time. Instead of using the `synchronized` keyword on the methods to be synchronized, the object which implements the Lockable interface handles the request.
In this example, we have a `SwordOfAragorn` object that implements the `Lockable` interface. Multiple `Creature` objects, represented by `Elf`, `Orc`, and `Human` classes, are trying to acquire the sword. Each `Creature` is wrapped in a `Feind` object that implements `Runnable`, allowing each creature to attempt to acquire the sword in a separate thread.
## Code Snippets
Here's the `Lockable` interface:
```java
/** This interface describes the methods to be supported by a lockable object. */
publicinterfaceLockable{
/**
* Checks if the object is locked.
*
* @return true if it is locked.
*/
booleanisLocked();
/**
* locks the object with the creature as the locker.
*
* @param creature as the locker.
* @return true if the object was locked successfully.
*/
booleanlock(Creaturecreature);
/**
* Unlocks the object.
*
* @param creature as the locker.
*/
voidunlock(Creaturecreature);
/**
* Gets the locker.
*
* @return the Creature that holds the object. Returns null if no one is locking.
*/
CreaturegetLocker();
/**
* Returns the name of the object.
*
* @return the name of the object.
*/
StringgetName();
booleanacquire(Creaturecreature);
voidrelease(Creaturecreature);
}
```
We have defined that according to our context, the object must implement the Lockable interface.
For example, the SwordOfAragorn class:
The `SwordOfAragorn` class implements this interface:
```java
publicclassSwordOfAragornimplementsLockable{
privateCreaturelocker;
privatefinalObjectsynchronizer;
privatestaticfinalStringNAME="The Sword of Aragorn";
publicSwordOfAragorn(){
this.locker=null;
this.synchronizer=newObject();
}
@Override
publicbooleanisLocked(){
returnthis.locker!=null;
}
@Override
publicbooleanlock(@NonNullCreaturecreature){
synchronized(synchronizer){
LOGGER.info("{} is now trying to acquire {}!",creature.getName(),this.getName());
LOGGER.info("The master of the sword is now {}.",sword.getLocker().getName());
}
}catch(InterruptedExceptione){
LOGGER.error(e.getMessage());
Thread.currentThread().interrupt();
}finally{
service.shutdown();
}
// Additional code...
}
}
```
## Applicability
The Lockable Object pattern is ideal for non distributed applications, that needs to be thread-safe
and keeping their domain models in memory(in contrast to persisted models such as databases).
This example demonstrates the Lockable Object pattern by showing how multiple threads can attempt to acquire a lock on a shared resource, with only one thread being able to acquire the lock at a time.
## Class diagram


## Applicability
* Use the Lockable Object pattern when you need to prevent data corruption by multiple threads accessing a shared resource concurrently.
* Suitable for systems where thread safety is critical and data integrity must be maintained across various operations.
## Known Uses
* Java’s synchronized keyword and the Lock interfaces in the java.util.concurrent.locks package implement lockable objects to manage synchronization.
## Consequences
Benefits:
* Ensures data consistency and prevents race conditions.
* Provides clear structure for managing access to shared resources.
Trade-offs:
* Can lead to decreased performance due to overhead of acquiring and releasing locks.
* Potential for deadlocks if not implemented and managed carefully.
## Related Patterns
[Monitor Object](https://java-design-patterns.com/patterns/monitor/): Both patterns manage access to shared resources; Monitor Object combines synchronization and encapsulation of the condition variable.
[Read/Write Lock](https://java-design-patterns.com/patterns/reader-writer-lock/): Specialization of Lockable Object for scenarios where read operations outnumber write operations.
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.