diff --git a/lockable-object/README.md b/lockable-object/README.md index f0dbfd60e..c4bfef6a8 100644 --- a/lockable-object/README.md +++ b/lockable-object/README.md @@ -3,281 +3,161 @@ title: Lockable Object category: Concurrency language: en tag: -- Performance + - Decoupling + - Encapsulation + - Security + - Synchronization + - Thread management --- +## Also known as + +* Resource Lock +* Mutual Exclusion Object ## Intent -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. */ public interface Lockable { - - /** - * Checks if the object is locked. - * - * @return true if it is locked. - */ boolean isLocked(); - - /** - * locks the object with the creature as the locker. - * - * @param creature as the locker. - * @return true if the object was locked successfully. - */ - boolean lock(Creature creature); - - /** - * Unlocks the object. - * - * @param creature as the locker. - */ - void unlock(Creature creature); - - /** - * Gets the locker. - * - * @return the Creature that holds the object. Returns null if no one is locking. - */ Creature getLocker(); - - /** - * Returns the name of the object. - * - * @return the name of the object. - */ - String getName(); + boolean acquire(Creature creature); + void release(Creature creature); } - ``` -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 public class SwordOfAragorn implements Lockable { - - private Creature locker; - private final Object synchronizer; - private static final String NAME = "The Sword of Aragorn"; - - public SwordOfAragorn() { - this.locker = null; - this.synchronizer = new Object(); - } - - @Override - public boolean isLocked() { - return this.locker != null; - } - - @Override - public boolean lock(@NonNull Creature creature) { - synchronized (synchronizer) { - LOGGER.info("{} is now trying to acquire {}!", creature.getName(), this.getName()); - if (!isLocked()) { - locker = creature; - return true; - } else { - if (!locker.getName().equals(creature.getName())) { - return false; - } - } - } - return false; - } - - @Override - public void unlock(@NonNull Creature creature) { - synchronized (synchronizer) { - if (locker != null && locker.getName().equals(creature.getName())) { - locker = null; - LOGGER.info("{} is now free!", this.getName()); - } - if (locker != null) { - throw new LockingException("You cannot unlock an object you are not the owner of."); - } - } - } - - @Override - public Creature getLocker() { - return this.locker; - } - - @Override - public String getName() { - return NAME; - } + // Implementation details... } ``` -According to our context, there are creatures that are looking for the sword, so must define the parent class: +The `Creature` class and its subclasses (`Elf`, `Orc`, `Human`) represent different creatures that can try to acquire the sword: ```java public abstract class Creature { + // Implementation details... +} - private String name; - private CreatureType type; - private int health; - private int damage; - Set instruments; +public class Elf extends Creature { + // Implementation details... +} - protected Creature(@NonNull String name) { - this.name = name; - this.instruments = new HashSet<>(); - } - - /** - * Reaches for the Lockable and tried to hold it. - * - * @param lockable as the Lockable to lock. - * @return true of Lockable was locked by this creature. - */ - public boolean acquire(@NonNull Lockable lockable) { - if (lockable.lock(this)) { - instruments.add(lockable); - return true; - } - return false; - } - - /** Terminates the Creature and unlocks all of the Lockable that it posses. */ - public synchronized void kill() { - LOGGER.info("{} {} has been slayed!", type, name); - for (Lockable lockable : instruments) { - lockable.unlock(this); - } - this.instruments.clear(); - } - - /** - * Attacks a foe. - * - * @param creature as the foe to be attacked. - */ - public synchronized void attack(@NonNull Creature creature) { - creature.hit(getDamage()); - } - - /** - * When a creature gets hit it removed the amount of damage from the creature's life. - * - * @param damage as the damage that was taken. - */ - public synchronized void hit(int damage) { - if (damage < 0) { - throw new IllegalArgumentException("Damage cannot be a negative number"); - } - if (isAlive()) { - setHealth(getHealth() - damage); - if (!isAlive()) { - kill(); - } - } - } - - /** - * Checks if the creature is still alive. - * - * @return true of creature is alive. - */ - public synchronized boolean isAlive() { - return getHealth() > 0; - } +public class Orc extends Creature { + // Implementation details... +} +public class Human extends Creature { + // Implementation details... } ``` -As mentioned before, we have classes that extend the Creature class, such as Elf, Orc, and Human. - -Finally, the following program will simulate a battle for the sword: +The `Feind` class wraps a `Creature` and a `Lockable` object, and implements `Runnable`: ```java -public class App implements Runnable { +public class Feind implements Runnable { + private final Creature creature; + private final Lockable target; - private static final int WAIT_TIME = 3; - private static final int WORKERS = 2; - private static final int MULTIPLICATION_FACTOR = 3; - - /** - * main method. - * - * @param args as arguments for the main method. - */ - public static void main(String[] args) { - var app = new App(); - app.run(); + public Feind(@NonNull Creature feind, @NonNull Lockable target) { + this.creature = feind; + this.target = target; } @Override public void run() { - // The target object for this example. - var sword = new SwordOfAragorn(); - // Creation of creatures. - List creatures = new ArrayList<>(); - for (var i = 0; i < WORKERS; i++) { - creatures.add(new Elf(String.format("Elf %s", i))); - creatures.add(new Orc(String.format("Orc %s", i))); - creatures.add(new Human(String.format("Human %s", i))); + if (!creature.acquire(target)) { + fightForTheSword(creature, target.getLocker(), target); + } else { + LOGGER.info("{} has acquired the sword!", target.getLocker().getName()); } - int totalFiends = WORKERS * MULTIPLICATION_FACTOR; + } + + // Additional methods... +} +``` + +In the `App` class, multiple `Feind` objects are created and submitted to an `ExecutorService`, each in a separate thread: + +```java +public class App implements Runnable { + @Override + public void run() { + var sword = new SwordOfAragorn(); + List creatures = new ArrayList<>(); + // Creation of creatures... ExecutorService service = Executors.newFixedThreadPool(totalFiends); - // Attach every creature and the sword is a Fiend to fight for the sword. for (var i = 0; i < totalFiends; i = i + MULTIPLICATION_FACTOR) { service.submit(new Feind(creatures.get(i), sword)); service.submit(new Feind(creatures.get(i + 1), sword)); service.submit(new Feind(creatures.get(i + 2), sword)); } - // Wait for program to terminate. - try { - if (!service.awaitTermination(WAIT_TIME, TimeUnit.SECONDS)) { - LOGGER.info("The master of the sword is now {}.", sword.getLocker().getName()); - } - } catch (InterruptedException e) { - 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 -![alt text](./etc/lockable-object.urm.png "Lockable Object class diagram") +![Lockable Object](./etc/lockable-object.urm.png "Lockable Object 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. ## Credits -* [Lockable Object - Chapter 10.3, J2EE Design Patterns, O'Reilly](http://ommolketab.ir/aaf-lib/axkwht7wxrhvgs2aqkxse8hihyu9zv.pdf) +* [Java Concurrency in Practice](https://amzn.to/4aRMruW) +* [Pattern-Oriented Software Architecture Volume 2: Patterns for Concurrent and Networked Objects](https://amzn.to/3UgC24V) diff --git a/lockable-object/src/main/java/com/iluwatar/lockableobject/App.java b/lockable-object/src/main/java/com/iluwatar/lockableobject/App.java index 5ec59b69d..b87381eaf 100644 --- a/lockable-object/src/main/java/com/iluwatar/lockableobject/App.java +++ b/lockable-object/src/main/java/com/iluwatar/lockableobject/App.java @@ -42,8 +42,8 @@ import lombok.extern.slf4j.Slf4j; * the request. * *

In this example, we create a new Lockable object with the SwordOfAragorn implementation of it. - * Afterwards we create 6 Creatures with the Elf, Orc and Human implementations and assign them each - * to a Fiend object and the Sword is the target object. Because there is only one Sword and it uses + * Afterward we create 6 Creatures with the Elf, Orc and Human implementations and assign them each + * to a Fiend object and the Sword is the target object. Because there is only one Sword, and it uses * the Lockable Object pattern, only one creature can hold the sword at a given time. When the sword * is locked, any other alive Fiends will try to lock, which will result in a race to lock the * sword. diff --git a/lockable-object/src/main/java/com/iluwatar/lockableobject/LockingException.java b/lockable-object/src/main/java/com/iluwatar/lockableobject/LockingException.java index dfbe1aeb4..8d9038f53 100644 --- a/lockable-object/src/main/java/com/iluwatar/lockableobject/LockingException.java +++ b/lockable-object/src/main/java/com/iluwatar/lockableobject/LockingException.java @@ -24,11 +24,14 @@ */ package com.iluwatar.lockableobject; +import java.io.Serial; + /** * An exception regarding the locking process of a Lockable object. */ public class LockingException extends RuntimeException { + @Serial private static final long serialVersionUID = 8556381044865867037L; public LockingException(String message) { diff --git a/lockable-object/src/main/java/com/iluwatar/lockableobject/domain/Creature.java b/lockable-object/src/main/java/com/iluwatar/lockableobject/domain/Creature.java index 1a02942d8..4380e7755 100644 --- a/lockable-object/src/main/java/com/iluwatar/lockableobject/domain/Creature.java +++ b/lockable-object/src/main/java/com/iluwatar/lockableobject/domain/Creature.java @@ -66,7 +66,7 @@ public abstract class Creature { return false; } - /** Terminates the Creature and unlocks all of the Lockable that it posses. */ + /** Terminates the Creature and unlocks all the Lockable that it possesses. */ public synchronized void kill() { LOGGER.info("{} {} has been slayed!", type, name); for (Lockable lockable : instruments) { diff --git a/lockable-object/src/main/java/com/iluwatar/lockableobject/domain/CreatureStats.java b/lockable-object/src/main/java/com/iluwatar/lockableobject/domain/CreatureStats.java index 045269d90..1d2a4040f 100644 --- a/lockable-object/src/main/java/com/iluwatar/lockableobject/domain/CreatureStats.java +++ b/lockable-object/src/main/java/com/iluwatar/lockableobject/domain/CreatureStats.java @@ -24,6 +24,8 @@ */ package com.iluwatar.lockableobject.domain; +import lombok.Getter; + /** Attribute constants of each Creature implementation. */ public enum CreatureStats { ELF_HEALTH(90), @@ -33,13 +35,10 @@ public enum CreatureStats { HUMAN_HEALTH(60), HUMAN_DAMAGE(60); - int value; + @Getter + final int value; - private CreatureStats(int value) { + CreatureStats(int value) { this.value = value; } - - public int getValue() { - return this.value; - } } diff --git a/lockable-object/src/main/java/com/iluwatar/lockableobject/domain/Feind.java b/lockable-object/src/main/java/com/iluwatar/lockableobject/domain/Feind.java index 08adcaee8..4bee7024f 100644 --- a/lockable-object/src/main/java/com/iluwatar/lockableobject/domain/Feind.java +++ b/lockable-object/src/main/java/com/iluwatar/lockableobject/domain/Feind.java @@ -30,7 +30,7 @@ import lombok.NonNull; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -/** A Feind is a creature that all it wants is to posses a Lockable object. */ +/** A Feind is a creature that wants to possess a Lockable object. */ public class Feind implements Runnable { private final Creature creature; @@ -53,12 +53,7 @@ public class Feind implements Runnable { @Override public void run() { if (!creature.acquire(target)) { - try { - fightForTheSword(creature, target.getLocker(), target); - } catch (InterruptedException e) { - LOGGER.error(e.getMessage()); - Thread.currentThread().interrupt(); - } + fightForTheSword(creature, target.getLocker(), target); } else { LOGGER.info("{} has acquired the sword!", target.getLocker().getName()); } @@ -69,11 +64,9 @@ public class Feind implements Runnable { * * @param reacher as the source creature. * @param holder as the foe. - * @param sword as the Lockable to posses. - * @throws InterruptedException in case of interruption. + * @param sword as the Lockable to possess. */ - private void fightForTheSword(Creature reacher, @NonNull Creature holder, Lockable sword) - throws InterruptedException { + private void fightForTheSword(Creature reacher, @NonNull Creature holder, Lockable sword) { LOGGER.info("A duel between {} and {} has been started!", reacher.getName(), holder.getName()); boolean randBool; while (this.target.isLocked() && reacher.isAlive() && holder.isAlive()) { diff --git a/lockable-object/src/main/java/com/iluwatar/lockableobject/domain/Human.java b/lockable-object/src/main/java/com/iluwatar/lockableobject/domain/Human.java index 1ba12aac0..c079ab376 100644 --- a/lockable-object/src/main/java/com/iluwatar/lockableobject/domain/Human.java +++ b/lockable-object/src/main/java/com/iluwatar/lockableobject/domain/Human.java @@ -28,7 +28,7 @@ package com.iluwatar.lockableobject.domain; public class Human extends Creature { /** - * A constructor that initializes the attributes of an human. + * A constructor that initializes the attributes of a human. * * @param name as the name of the creature. */ diff --git a/lockable-object/src/main/java/com/iluwatar/lockableobject/domain/Orc.java b/lockable-object/src/main/java/com/iluwatar/lockableobject/domain/Orc.java index 747c7a1ab..0f13fcc0d 100644 --- a/lockable-object/src/main/java/com/iluwatar/lockableobject/domain/Orc.java +++ b/lockable-object/src/main/java/com/iluwatar/lockableobject/domain/Orc.java @@ -24,7 +24,7 @@ */ package com.iluwatar.lockableobject.domain; -/** A Orc implementation of a Creature. */ +/** An Orc implementation of a Creature. */ public class Orc extends Creature { /** * A constructor that initializes the attributes of an orc. diff --git a/lockable-object/src/test/java/com/iluwatar/lockableobject/CreatureTest.java b/lockable-object/src/test/java/com/iluwatar/lockableobject/CreatureTest.java index b8f9806a6..f2fec0531 100644 --- a/lockable-object/src/test/java/com/iluwatar/lockableobject/CreatureTest.java +++ b/lockable-object/src/test/java/com/iluwatar/lockableobject/CreatureTest.java @@ -90,7 +90,7 @@ class CreatureTest { Assertions.assertEquals(orc, sword.getLocker()); } - void killCreature(Creature source, Creature target) throws InterruptedException { + void killCreature(Creature source, Creature target) { while (target.isAlive()) { source.attack(target); } diff --git a/lockable-object/src/test/java/com/iluwatar/lockableobject/ExceptionsTest.java b/lockable-object/src/test/java/com/iluwatar/lockableobject/ExceptionsTest.java index 64f8f3bdd..614ed9655 100644 --- a/lockable-object/src/test/java/com/iluwatar/lockableobject/ExceptionsTest.java +++ b/lockable-object/src/test/java/com/iluwatar/lockableobject/ExceptionsTest.java @@ -29,17 +29,17 @@ import org.junit.jupiter.api.Test; class ExceptionsTest { - private String msg = "test"; + private static final String MSG = "test"; @Test void testException(){ Exception e; try{ - throw new LockingException(msg); + throw new LockingException(MSG); } catch(LockingException ex){ e = ex; } - Assertions.assertEquals(msg, e.getMessage()); + Assertions.assertEquals(MSG, e.getMessage()); } }