Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added Join Pattern #3172

Open
wants to merge 7 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
135 changes: 135 additions & 0 deletions join/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
---
title: "Join Pattern in Java: Streamlining Concurrent Operations"
shortTitle: Join
description: "Master the Join Design Pattern in Java to coordinate and synchronize concurrent tasks effectively. Explore examples, code implementations, benefits, and practical applications."
category: Concurrency
language: en
tag:
- Concurrency
- Synchronization
- Parallel processing
- Gang of Four
---

## Also known as

* Fork-Join Pattern

## Intent of Join Pattern

The Join Pattern in Java focuses on coordinating and synchronizing concurrent tasks to achieve a specific outcome. It ensures that multiple tasks can execute independently, and their results are merged once all tasks complete.

## Detailed Explanation of Join Pattern with Real-World Examples

Real-world example

> Imagine a multi-chef kitchen preparing different dishes for a single order. Each chef works independently on their assigned dish, but the order cannot be delivered until every dish is ready. The kitchen manager, acting as the join point, ensures synchronization and prepares the final order once all dishes are done. Similarly, the Join Pattern allows tasks to execute concurrently and synchronizes their results for a final outcome.

In plain words

> The Join Pattern helps in synchronizing multiple independent tasks, allowing them to work concurrently and combining their outcomes efficiently.

Wikipedia says

> The join design pattern is a parallel processing pattern that helps merge results of concurrently executed tasks.

## Programmatic Example of Join Pattern in Java

In this example, we demonstrate how the Join Pattern can be implemented to manage multiple threads and synchronize their results. We use a task aggregator that collects data from individual tasks and combines it into a final result.

```java

package com.iluwatar.join;

import lombok.extern.slf4j.Slf4j;

/** Here main thread will execute after completion of 4 demo threads
* main thread will continue when CountDownLatch count becomes 0
* CountDownLatch will start with count 4 and 4 demo threads will decrease it by 1
* everytime when they will finish .
*/
Comment on lines +42 to +50
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The programmatic example in README.md should be minimalistic. It doesn't have to compile. The main purpose is to explain the reader how the pattern works using code snippets.


@Slf4j
public class JoinPatternDemo {

/**
* execution of demo and dependent threads.
*/
public static void main(String[] args) {

int[] executionOrder = {4, 2, 1, 3};
int noOfDemoThreads = 4;
int noOfDependentThreads = 2;
JoinPattern pattern = new JoinPattern(noOfDemoThreads, executionOrder);
Thread previous = null;

for (int i = 0; i < noOfDemoThreads; i++) {
previous = new Thread(new DemoThread(executionOrder[i], previous));
previous.start();
}
pattern.await();

//Dependent threads after execution of DemoThreads
for (int i = 0; i < noOfDependentThreads; i++) {
new DependentThread(i + 1).start();
}
LOGGER.info("end of program ");

}

}

```

### Program Output:

```
Running com.iluwatar.join.JoinPatternTest
01:13:17.890 [Thread-2] INFO com.iluwatar.join.DemoThread -- Thread 1 starts
01:13:18.167 [Thread-2] INFO com.iluwatar.join.DemoThread -- Thread 1 ends
01:13:18.168 [Thread-3] INFO com.iluwatar.join.DemoThread -- Thread 4 starts
01:13:19.176 [Thread-3] INFO com.iluwatar.join.DemoThread -- Thread 4 ends
01:13:19.176 [Thread-4] INFO com.iluwatar.join.DemoThread -- Thread 3 starts
01:13:19.935 [Thread-4] INFO com.iluwatar.join.DemoThread -- Thread 3 ends
01:13:19.935 [Thread-5] INFO com.iluwatar.join.DemoThread -- Thread 2 starts
01:13:20.437 [Thread-5] INFO com.iluwatar.join.DemoThread -- Thread 2 ends
```

## When to Use the Join Pattern in Java

Use the Join Pattern in Java:

* To synchronize results from multiple independent tasks executing in parallel.
* To aggregate and process data from various sources concurrently.
* To reduce the complexity of managing multiple threads in parallel operations.

## Real-World Applications of Join Pattern in Java

* Managing concurrent HTTP requests and aggregating their responses into a single result.
* Parallel processing of large datasets, such as in map-reduce frameworks.
* Synchronizing asynchronous operations, e.g., CompletableFutures in Java.

## Benefits and Trade-offs of Join Pattern

### Benefits:

* Efficiently handles parallel processing tasks with minimal synchronization overhead.
* Improves application performance by utilizing available system resources optimally.
* Simplifies the logic for managing and synchronizing multiple tasks.

### Trade-offs:

* Debugging can become challenging with large numbers of asynchronous tasks.
* Improper use may lead to deadlocks or performance bottlenecks.

## Related Java Design Patterns

* [Fork-Join Framework](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ForkJoinPool.html): Built-in Java framework for recursive task splitting and joining.
* [Future and CompletableFuture](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletableFuture.html): Used for handling and synchronizing asynchronous operations.
* [Observer Pattern](https://java-design-patterns.com/patterns/observer/): Can be combined with Join to monitor task progress.

## References and Credits

* [Java Concurrency in Practice](https://amzn.to/3sfS8mT)
* [Effective Java](https://amzn.to/3GxS8p4)
* [Oracle Java Documentation on Concurrency](https://docs.oracle.com/javase/tutorial/essential/concurrency/)
Binary file added join/etc/JoinPatternFlowDiagram.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added join/etc/java-join-method.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
37 changes: 37 additions & 0 deletions join/etc/join.urm.puml
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
@startuml
package com.iluwatar.join {
class DemoThread {
- LOGGER : Logger {static}
- actualExecutionOrder : int[] {static}
- executionOrder : int[] {static}
- id : int
- index : int {static}
- pattern : JoinPattern {static}
- previous : Thread
+ DemoThread(id : int, previous : Thread)
+ getActualExecutionOrder() : int[] {static}
+ run()
+ setExecutionOrder(executionOrder : int[], pattern : JoinPattern) {static}
}
class DependentThread {
- LOGGER : Logger {static}
- id : int
~ DependentThread(id : int)
+ run()
}
class JoinPattern {
~ executionOrder : int[]
- latch : CountDownLatch
~ noOfDemoThreads : int
+ JoinPattern(noOfDemoThreads : int, executionOrder : int[])
+ await()
+ countdown()
}
class JoinPatternDemo {
- LOGGER : Logger {static}
+ JoinPatternDemo()
+ main(String[]) {static}
}
}
DemoThread --> "-pattern" JoinPattern
@enduml
72 changes: 72 additions & 0 deletions join/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--

This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).

The MIT License
Copyright © 2014-2022 Ilkka Seppälä

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.iluwatar</groupId>
<artifactId>java-design-patterns</artifactId>
<version>1.26.0-SNAPSHOT</version>
</parent>
<artifactId>join</artifactId>
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-params</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<executions>
<execution>
<configuration>
<archive>
<manifest>
<mainClass>com.iluwatar.join.JoinPatternDemo</mainClass>
</manifest>
</archive>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
85 changes: 85 additions & 0 deletions join/src/main/java/com/iluwatar/join/DemoThread.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
/*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.join;

import lombok.extern.slf4j.Slf4j;

/**
* demo threads implementing Runnable .
*/
@Slf4j
public class DemoThread implements Runnable {

private static int[] executionOrder;
private static int[] actualExecutionOrder;
private static int index = 0;
private static JoinPattern pattern;
private int id;
private Thread previous;

/**
* Initalise a demo thread object with id and previous thread .
*/
public DemoThread(int id, Thread previous) {
this.id = id;
this.previous = previous;

}

public static int[] getActualExecutionOrder() {
return actualExecutionOrder;
}
/**
* set custom execution order of threads .
*/
public static void setExecutionOrder(int[] executionOrder, JoinPattern pattern) {
DemoThread.executionOrder = executionOrder;
DemoThread.pattern = pattern;
actualExecutionOrder = new int[executionOrder.length];
}
/**
* use to run demo thread.
*/
public void run() {
if (previous != null) {
try {
previous.join();
} catch (InterruptedException e) {
e.printStackTrace();
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Log to Slf4j log, not to console, e.g.

log.error("An error occurred: {}", e.getMessage(), e);

}
}
LOGGER.info("Thread " + id + " starts");
try {
Thread.sleep(id * 250);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
LOGGER.info("Thread " + id + " ends");
actualExecutionOrder[index++] = id;
pattern.countdown();
}
}

}
57 changes: 57 additions & 0 deletions join/src/main/java/com/iluwatar/join/DependentThread.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
/*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.join;

import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
* Dependent threads will execute only after completion of all demothreads.
*/
@Slf4j
public class DependentThread implements Runnable {


private int id;
DependentThread(int id) {
this.id = id;
}
/**
* dependent threads run .
*/
public void run() {

LOGGER.info(" Dependent Thread " + id + " starts ");
try {
Thread.sleep(id * 200);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
LOGGER.info("Dependent Thread " + id + " completed ");
}

}
}
Loading
Loading