forked from iluwatar/java-design-patterns
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge remote-tracking branch 'origin/master'
- Loading branch information
Showing
53 changed files
with
1,296 additions
and
719 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,22 +1,124 @@ | ||
--- | ||
title: Double Checked Locking | ||
category: Idiom | ||
title: Double-Checked Locking | ||
category: Concurrency | ||
language: en | ||
tag: | ||
- Performance | ||
- Optimization | ||
- Performance | ||
--- | ||
|
||
## Intent | ||
Reduce the overhead of acquiring a lock by first testing the | ||
locking criterion (the "lock hint") without actually acquiring the lock. Only | ||
if the locking criterion check indicates that locking is required does the | ||
actual locking logic proceed. | ||
|
||
The Double-Checked Locking pattern aims to reduce the overhead of acquiring a lock by first testing the locking criterion (the 'lock hint') without actually acquiring the lock. Only if the locking criterion check indicates that locking is necessary does the actual locking logic proceed. | ||
|
||
## Explanation | ||
|
||
Real world example | ||
|
||
> In a company with a high-value equipment room, employees first check a visible sign to see if the room is locked. If the sign shows it's unlocked, they enter directly; if locked, they use a security keycard for access. This two-step verification process efficiently manages security without unnecessary use of the electronic lock system, mirroring the Double-Checked Locking pattern used in software to minimize resource-intensive operations. | ||
In plain words | ||
|
||
> The Double-Checked Locking pattern in software minimizes costly locking operations by first checking the lock status in a low-cost manner before proceeding with a more resource-intensive lock, ensuring efficiency and thread safety during object initialization. | ||
Wikipedia says | ||
|
||
> In software engineering, double-checked locking (also known as "double-checked locking optimization") is a software design pattern used to reduce the overhead of acquiring a lock by testing the locking criterion (the "lock hint") before acquiring the lock. Locking occurs only if the locking criterion check indicates that locking is required. | ||
**Programmatic Example** | ||
|
||
The Double-Checked Locking pattern is used in the HolderThreadSafe class to ensure that the Heavy object is only created once, even when accessed from multiple threads. Here's how it works: | ||
|
||
Check if the object is initialized (first check): If it is, return it immediately. | ||
|
||
```java | ||
if (heavy == null) { | ||
// ... | ||
} | ||
``` | ||
|
||
Synchronize the block of code where the object is created: This ensures that only one thread can create the object. | ||
|
||
```java | ||
synchronized (this) { | ||
// ... | ||
} | ||
``` | ||
|
||
Check again if the object is initialized (second check): If another thread has already created the object by the time the current thread enters the synchronized block, return the created object. | ||
|
||
```java | ||
if (heavy == null) { | ||
heavy = new Heavy(); | ||
} | ||
``` | ||
|
||
Return the created object. | ||
|
||
```java | ||
return heavy; | ||
``` | ||
|
||
Here's the complete code for the HolderThreadSafe class: | ||
|
||
```java | ||
public class HolderThreadSafe { | ||
|
||
private Heavy heavy; | ||
|
||
public HolderThreadSafe() { | ||
LOGGER.info("Holder created"); | ||
} | ||
|
||
public synchronized Heavy getHeavy() { | ||
if (heavy == null) { | ||
synchronized (this) { | ||
if (heavy == null) { | ||
heavy = new Heavy(); | ||
} | ||
} | ||
} | ||
return heavy; | ||
} | ||
} | ||
``` | ||
|
||
In this code, the Heavy object is only created when the getHeavy() method is called for the first time. This is known as lazy initialization. The double-checked locking pattern is used to ensure that the Heavy object is only created once, even when the getHeavy() method is called from multiple threads simultaneously. | ||
|
||
## Class diagram | ||
![alt text](./etc/double_checked_locking_1.png "Double Checked Locking") | ||
|
||
![Double-Check Locking](./etc/double_checked_locking_1.png "Double-Checked Locking") | ||
|
||
## Applicability | ||
Use the Double Checked Locking pattern when | ||
|
||
* there is a concurrent access in object creation, e.g. singleton, where you want to create single instance of the same class and checking if it's null or not maybe not be enough when there are two or more threads that checks if instance is null or not. | ||
* there is a concurrent access on a method where method's behaviour changes according to the some constraints and these constraint change within this method. | ||
This pattern is used in scenarios where: | ||
|
||
* There is a significant performance cost associated with acquiring a lock, and | ||
* The lock is not frequently needed. | ||
|
||
## Known Uses | ||
|
||
* Singleton pattern implementation in multithreading environments. | ||
* Lazy initialization of resource-intensive objects in Java applications. | ||
|
||
## Consequences | ||
|
||
Benefits: | ||
|
||
* Performance gains from avoiding unnecessary locking after the object is initialized. | ||
* Thread safety is maintained for critical initialization sections. | ||
|
||
Trade-offs: | ||
|
||
* Complex implementation can lead to mistakes, such as incorrect publishing of objects due to memory visibility issues. | ||
* In Java, it can be redundant or broken in some versions unless volatile variables are used with care. | ||
|
||
## Related Patterns | ||
|
||
* [Singleton](https://java-design-patterns.com/patterns/singleton/): Double-Checked Locking is often used in implementing thread-safe Singletons. | ||
* [Lazy Loading](https://java-design-patterns.com/patterns/lazy-loading/): Shares the concept of delaying object creation until necessary. | ||
|
||
## Credits | ||
|
||
* [Java Concurrency in Practice](https://amzn.to/4aIAPKa) | ||
* [Effective Java](https://amzn.to/3xx7KDh) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,23 +1,110 @@ | ||
--- | ||
title: Double Dispatch | ||
category: Idiom | ||
category: Behavioral | ||
language: en | ||
tag: | ||
- Extensibility | ||
- Polymorphism | ||
--- | ||
|
||
## Also known as | ||
|
||
* Multi-methods | ||
|
||
## Intent | ||
Double Dispatch pattern is a way to create maintainable dynamic | ||
behavior based on receiver and parameter types. | ||
|
||
The Double Dispatch pattern is used to achieve dynamic polymorphism based on the types of two objects involved in a method call. It allows method behavior to be different based on the combination of the runtime types of both the object on which the method is called and the object being passed as a parameter. | ||
|
||
## Explanation | ||
|
||
Real world example | ||
|
||
> In a logistics company, different types of delivery vehicles like trucks, drones, and bikes interact with various types of packages (fragile, oversized, standard). The Double Dispatch design pattern is used to determine the optimal delivery method: trucks might handle oversized items, drones for quick deliveries of light packages, and bikes for urban areas. Each vehicle-package combination results in a different handling and delivery strategy, dynamically determined at runtime based on the types of both the vehicle and the package. | ||
In plain words | ||
|
||
> The Double Dispatch design pattern allows a program to select a different function to execute based on the types of two objects involved in a call, enhancing flexibility in handling interactions between them. | ||
Wikipedia says | ||
|
||
> In software engineering, double dispatch is a special form of multiple dispatch, and a mechanism that dispatches a function call to different concrete functions depending on the runtime types of two objects involved in the call. In most object-oriented systems, the concrete function that is called from a function call in the code depends on the dynamic type of a single object and therefore they are known as single dispatch calls, or simply virtual function calls. | ||
**Programmatic Example** | ||
|
||
The Double Dispatch pattern is used to handle collisions between different types of game objects. Each game object is an instance of a class that extends the GameObject abstract class. The GameObject class has a collision(GameObject) method, which is overridden in each subclass to define the behavior when a collision occurs with another game object. Here is a simplified version of the GameObject class and its subclasses: | ||
|
||
```java | ||
public abstract class GameObject { | ||
// Other properties and methods... | ||
|
||
public abstract void collision(GameObject gameObject); | ||
} | ||
|
||
public class FlamingAsteroid extends GameObject { | ||
// Other properties and methods... | ||
|
||
@Override | ||
public void collision(GameObject gameObject) { | ||
gameObject.collisionWithFlamingAsteroid(this); | ||
} | ||
} | ||
|
||
public class SpaceStationMir extends GameObject { | ||
// Other properties and methods... | ||
|
||
@Override | ||
public void collision(GameObject gameObject) { | ||
gameObject.collisionWithSpaceStationMir(this); | ||
} | ||
} | ||
``` | ||
|
||
In the App class, the Double Dispatch pattern is used to check for collisions between all pairs of game objects: | ||
|
||
```java | ||
objects.forEach(o1 -> objects.forEach(o2 -> { | ||
if (o1 != o2 && o1.intersectsWith(o2)) { | ||
o1.collision(o2); | ||
} | ||
})); | ||
``` | ||
|
||
When a collision is detected between two objects, the collision(GameObject) method is called on the first object (o1) with the second object (o2) as the argument. This method call is dispatched at runtime to the appropriate collision(GameObject) method in the class of o1. Inside this method, another method call gameObject.collisionWithX(this) is made on o2 (where X is the type of o1), which is dispatched at runtime to the appropriate collisionWithX(GameObject) method in the class of o2. This is the "double dispatch" - two method calls are dispatched at runtime based on the types of two objects. | ||
|
||
## Class diagram | ||
![alt text](./etc/double-dispatch.png "Double Dispatch") | ||
|
||
![Double Dispatch](./etc/double-dispatch.png "Double Dispatch") | ||
|
||
## Applicability | ||
Use the Double Dispatch pattern when | ||
|
||
* the dynamic behavior is not defined only based on receiving object's type but also on the receiving method's parameter type. | ||
* When the behavior of a method needs to vary not just based on the object it is called on, but also based on the type of the argument. | ||
* In scenarios where if-else or switch-case type checks against the type of objects are cumbersome and not scalable. | ||
* When implementing operations in domain classes without contaminating their code with complex decision-making logic about other domain classes. | ||
|
||
## Known Uses | ||
|
||
* Graphical user interfaces where different actions are taken based on different types of mouse events interacting with different types of elements. | ||
* Simulation systems where interactions between different types of objects need to trigger distinct behaviors. | ||
|
||
## Consequences | ||
|
||
Benefits: | ||
|
||
* Increases the flexibility of code by handling interaction between objects in a manner that is easy to understand and maintain. | ||
* Helps in adhering to the [Open/Closed Principle](https://java-design-patterns.com/principles/#open-closed-principle) by allowing new classes to be introduced without modifying existing classes. | ||
|
||
Trade-offs: | ||
|
||
* Can lead to more complex code structures, especially in languages like Java that do not support this pattern natively. | ||
* May require additional effort in maintaining and extending as new classes are added. | ||
|
||
## Related Patterns | ||
|
||
* [Strategy](https://java-design-patterns.com/patterns/strategy/): Similar in intent where it's used to choose an algorithm at runtime, though Strategy focuses on single object context rather than interactions between multiple objects. | ||
* [Visitor](https://java-design-patterns.com/patterns/visitor/): Often used together with Double Dispatch to encapsulate operations performed on a set of element objects. | ||
|
||
## Real world examples | ||
|
||
* [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/4awj7cV) | ||
* [Java Design Pattern Essentials](https://amzn.to/3Jg8ZZV) | ||
* [Refactoring to Patterns](https://amzn.to/3vRBJ8k) | ||
* [ObjectOutputStream](https://docs.oracle.com/javase/8/docs/api/java/io/ObjectOutputStream.html) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.