-
-
Notifications
You must be signed in to change notification settings - Fork 26.8k
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
keshavMM004
wants to merge
10
commits into
iluwatar:master
Choose a base branch
from
keshavMM004:f2
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Added Join Pattern #3172
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
cf93fc8
Added Join Design Pattern Issue #70
keshavMM004 3e23c5e
resolved checkstyle violations
keshavMM004 3d474c4
resolved checkstyle conflicts
keshavMM004 1277bfc
corrected thread creation
keshavMM004 0b11c31
thrown exception
keshavMM004 78a8bab
Merge branch 'master' into f2
keshavMM004 2f249e8
Merge branch 'master' into f2
iluwatar 2ca371c
Merge branch 'master' of https://github.com/keshavMM004/java-design-p…
keshavMM004 3b4bc80
updated README.MD
keshavMM004 c2dfb65
Merge branch 'f2' of https://github.com/keshavMM004/java-design-patte…
keshavMM004 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,142 @@ | ||
--- | ||
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 . | ||
* DemoThreads are implemented in join pattern such that every newly created thread | ||
* waits for the completion of previous thread by previous.join() . Hence maintaining | ||
* execution order of demo threads . | ||
* JoinPattern object ensures that dependent threads execute only after completion of | ||
* demo threads by pattern.await() . This method keep the main thread in waiting state | ||
* until countdown latch becomes 0 . CountdownLatch will become 0 as all demo threads | ||
* will be completed as each of them have decreased it by 1 and its initial count was set to noOfDemoThreads. | ||
* Hence this pattern ensures dependent threads will start only after completion of demo threads . | ||
*/ | ||
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 "); | ||
|
||
/** | ||
* use to run demo thread. | ||
* every newly created thread waits for | ||
* the completion of previous thread | ||
* by previous.join() . | ||
*/ | ||
@Override | ||
public void run() { | ||
if (previous != null) { | ||
try { | ||
previous.join(); | ||
} catch (InterruptedException e) { | ||
Thread.currentThread().interrupt(); | ||
LOGGER.error("Interrupted exception : ", e); | ||
} | ||
} | ||
|
||
|
||
``` | ||
|
||
### Program Output: | ||
|
||
[INFO] Running com.iluwatar.join.JoinPatternTest | ||
16:12:01.815 [Thread-2] INFO com.iluwatar.join.DemoThread -- Thread 1 starts | ||
16:12:02.086 [Thread-2] INFO com.iluwatar.join.DemoThread -- Thread 1 ends | ||
16:12:02.087 [Thread-3] INFO com.iluwatar.join.DemoThread -- Thread 4 starts | ||
16:12:03.090 [Thread-3] INFO com.iluwatar.join.DemoThread -- Thread 4 ends | ||
16:12:03.091 [Thread-4] INFO com.iluwatar.join.DemoThread -- Thread 3 starts | ||
16:12:03.851 [Thread-4] INFO com.iluwatar.join.DemoThread -- Thread 3 ends | ||
16:12:03.851 [Thread-5] INFO com.iluwatar.join.DemoThread -- Thread 2 starts | ||
16:12:04.352 [Thread-5] INFO com.iluwatar.join.DemoThread -- Thread 2 ends | ||
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 2.904 s -- in com.iluwatar.join.JoinPatternTest | ||
[INFO] | ||
[INFO] Results: | ||
[INFO] | ||
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0 | ||
[INFO] | ||
|
||
## 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/) |
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
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 |
---|---|---|
@@ -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 |
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 |
---|---|---|
@@ -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> |
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 |
---|---|---|
@@ -0,0 +1,89 @@ | ||
/* | ||
* 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[] actualExecutionOrder; | ||
private static int index = 0; | ||
private static JoinPattern pattern; | ||
private final int id; | ||
private final Thread previous; | ||
|
||
/** | ||
* Initialise 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.pattern = pattern; | ||
actualExecutionOrder = new int[executionOrder.length]; | ||
} | ||
/** | ||
* use to run demo thread. | ||
* every newly created thread waits for | ||
* the completion of previous thread | ||
* by previous.join() . | ||
*/ | ||
@Override | ||
public void run() { | ||
if (previous != null) { | ||
try { | ||
previous.join(); | ||
} catch (InterruptedException e) { | ||
Thread.currentThread().interrupt(); | ||
LOGGER.error("Interrupted exception : ", e); | ||
} | ||
} | ||
LOGGER.info("Thread " + id + " starts"); | ||
try { | ||
Thread.sleep(id * (long) 250); | ||
} catch (InterruptedException e) { | ||
Thread.currentThread().interrupt(); | ||
LOGGER.error("Interrupted exception : ", e); | ||
} finally { | ||
LOGGER.info("Thread " + id + " ends"); | ||
actualExecutionOrder[index++] = id; | ||
pattern.countdown(); | ||
} | ||
} | ||
|
||
} |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Keep the code example minimal. Leave out headers and imports and such. It doesn't have to compile, but the reader has to understand.