Skip to content

Commit

Permalink
Merge remote-tracking branch 'origin/master'
Browse files Browse the repository at this point in the history
  • Loading branch information
Ehspresso committed Apr 17, 2024
2 parents f4ebf9c + e5f5d1b commit 5ef73bc
Show file tree
Hide file tree
Showing 53 changed files with 1,296 additions and 719 deletions.
18 changes: 18 additions & 0 deletions .all-contributorsrc
Original file line number Diff line number Diff line change
Expand Up @@ -3086,6 +3086,24 @@
"contributions": [
"code"
]
},
{
"login": "k1w1dev",
"name": "k1w1dev",
"avatar_url": "https://avatars.githubusercontent.com/u/121696782?v=4",
"profile": "https://github.com/k1w1dev",
"contributions": [
"code"
]
},
{
"login": "dev-yugantar",
"name": "dev-yugantar",
"avatar_url": "https://avatars.githubusercontent.com/u/153066190?v=4",
"profile": "https://github.com/dev-yugantar",
"contributions": [
"code"
]
}
],
"contributorsPerLine": 7,
Expand Down
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
[![Coverage](https://sonarcloud.io/api/project_badges/measure?project=iluwatar_java-design-patterns&metric=coverage)](https://sonarcloud.io/dashboard?id=iluwatar_java-design-patterns)
[![Join the chat at https://gitter.im/iluwatar/java-design-patterns](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/iluwatar/java-design-patterns?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
<!-- ALL-CONTRIBUTORS-BADGE:START - Do not remove or modify this section -->
[![All Contributors](https://img.shields.io/badge/all_contributors-338-orange.svg?style=flat-square)](#contributors-)
[![All Contributors](https://img.shields.io/badge/all_contributors-340-orange.svg?style=flat-square)](#contributors-)
<!-- ALL-CONTRIBUTORS-BADGE:END -->

<br/>
Expand Down Expand Up @@ -510,6 +510,8 @@ This project is licensed under the terms of the MIT license.
<tr>
<td align="center" valign="top" width="14.28%"><a href="https://github.com/Romo4ka-bot"><img src="https://avatars.githubusercontent.com/u/61774094?v=4?s=100" width="100px;" alt="Roman Leontev"/><br /><sub><b>Roman Leontev</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=Romo4ka-bot" title="Code">💻</a></td>
<td align="center" valign="top" width="14.28%"><a href="https://github.com/Ehspresso"><img src="https://avatars.githubusercontent.com/u/144370752?v=4?s=100" width="100px;" alt="Riley"/><br /><sub><b>Riley</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=Ehspresso" title="Code">💻</a></td>
<td align="center" valign="top" width="14.28%"><a href="https://github.com/k1w1dev"><img src="https://avatars.githubusercontent.com/u/121696782?v=4?s=100" width="100px;" alt="k1w1dev"/><br /><sub><b>k1w1dev</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=k1w1dev" title="Code">💻</a></td>
<td align="center" valign="top" width="14.28%"><a href="https://github.com/dev-yugantar"><img src="https://avatars.githubusercontent.com/u/153066190?v=4?s=100" width="100px;" alt="dev-yugantar"/><br /><sub><b>dev-yugantar</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=dev-yugantar" title="Code">💻</a></td>
</tr>
</tbody>
</table>
Expand Down
124 changes: 113 additions & 11 deletions double-checked-locking/README.md
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)
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,6 @@ class AppTest {

/**
* Issue: Add at least one assertion to this test case.
*
* Solution: Inserted assertion to check whether the execution of the main method in {@link App#main(String[])}
* throws an exception.
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ void tearDown() {
* item limit.
*/
@Test
void testAddItem() throws Exception {
void testAddItem() {
assertTimeout(ofMillis(10000), () -> {
// Create a new inventory with a limit of 1000 items and put some load on the add method
final var inventory = new Inventory(INVENTORY_SIZE);
Expand Down Expand Up @@ -109,7 +109,7 @@ void testAddItem() throws Exception {
}


private class InMemoryAppender extends AppenderBase<ILoggingEvent> {
private static class InMemoryAppender extends AppenderBase<ILoggingEvent> {
private final List<ILoggingEvent> log = new LinkedList<>();

public InMemoryAppender(Class clazz) {
Expand Down
101 changes: 94 additions & 7 deletions double-dispatch/README.md
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)
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,14 @@
*/
package com.iluwatar.doubledispatch;

import lombok.Getter;
import lombok.Setter;

/**
* Game objects have coordinates and some other status information.
*/
@Getter
@Setter
public abstract class GameObject extends Rectangle {

private boolean damaged;
Expand All @@ -42,22 +47,6 @@ public String toString() {
super.toString(), isDamaged(), isOnFire());
}

public boolean isOnFire() {
return onFire;
}

public void setOnFire(boolean onFire) {
this.onFire = onFire;
}

public boolean isDamaged() {
return damaged;
}

public void setDamaged(boolean damaged) {
this.damaged = damaged;
}

public abstract void collision(GameObject gameObject);

public abstract void collisionResolve(FlamingAsteroid asteroid);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,6 @@ class AppTest {

/**
* Issue: Add at least one assertion to this test case.
*
* Solution: Inserted assertion to check whether the execution of the main method in {@link App#main(String[])}
* throws an exception.
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ void testConstructor() {
* #toString()}
*/
@Test
void testToString() throws Exception {
void testToString() {
final var rectangle = new Rectangle(1, 2, 3, 4);
assertEquals("[1,2,3,4]", rectangle.toString());
}
Expand Down
Loading

0 comments on commit 5ef73bc

Please sign in to comment.