Structured Concurrency in Java
Last Updated :
14 May, 2023
Structured concurrency organizes concurrent processes in a controlled way to ease concurrent execution. It prevents race situations, deadlocks, and orphaned jobs. Structured concurrency may be implemented in Java utilizing libraries, frameworks, or experimental initiatives like Project Loom. Structured concurrency concepts and techniques in Java:
- ExecutorService and CompletableFuture
- ForkJoinPool and RecursiveTask
ExecutorService and CompletableFuture
ExecutorService in java.util.concurrent manages a pool of worker threads that may perform tasks simultaneously. CompletableFuture lets you link, manage, and combine tasks. ExecutorService and CompletableFuture provide systematic concurrency management of concurrent processes.
Example:
Java
// Java Program to demonstrate structured concurrency in
// Java using the ExecutorService and CompletableFuture
// classes from the java.util.concurrent package.
import java.util.concurrent.*;
// Driver class
public class StructuredConcurrencyExample {
// function main
public static void main(String[] args)
throws InterruptedException, ExecutionException
{
ExecutorService executor
= Executors.newFixedThreadPool(3);
CompletableFuture<Void> task1
= CompletableFuture.runAsync(() -> {
System.out.println("Task 1 started");
// Perform task 1
}, executor);
CompletableFuture<Void> task2
= CompletableFuture.runAsync(() -> {
System.out.println("Task 2 started");
// Perform task 2
}, executor);
CompletableFuture<Void> combinedTasks
= CompletableFuture.allOf(task1, task2);
// Waits for both tasks to complete
combinedTasks.get();
executor.shutdown();
}
}
OutputTask 1 started
Task 2 started
Note: The order of the task outputs may vary because the tasks are executed concurrently, and the order in which they complete may not be the same each time.
ForkJoinPool and RecursiveTask
ForkJoinPool, another concurrency framework in the java.util.concurrent package efficiently executes divide-and-conquer algorithms and steals work. ForkJoinPool with RecursiveTask or RecursiveAction creates organized concurrent tasks.
Example:
Java
// Java program to demonstrate the use of the ForkJoinPool
// to create organized concurrent tasks.
import java.util.concurrent.*;
public class StructuredConcurrencyExample {
public static void main(String[] args)
{
ForkJoinPool forkJoinPool = new ForkJoinPool();
// Task 1
RecursiveAction task1 = new RecursiveAction() {
@Override protected void compute()
{
// Perform task 1
System.out.println("Task 1 started");
}
};
// Task 2
RecursiveAction task2 = new RecursiveAction() {
@Override protected void compute()
{
// Perform task 2
System.out.println("Task 2 started");
}
};
// Submit both tasks and then join them
ForkJoinTask<Void> submittedTask1
= forkJoinPool.submit(task1);
ForkJoinTask<Void> submittedTask2
= forkJoinPool.submit(task2);
// Wait for both tasks to complete
submittedTask1.join();
submittedTask2.join();
forkJoinPool.shutdown();
}
}
OutputTask 1 started
Task 2 started
Note: The order of the task outputs may vary because the tasks are executed concurrently, and the order in which they complete may not be the same each time.
Similar Reads
Fork Java | Course Structure Course Home Page Week Topic Sub-Topic Week 1 Basics Of Java, Control Structures Background (JVM, JDK and JRE), Syntax, Variables, Data Types, I/O, Operators, Java packages If, If-else, Switch case, Loops(For, While, Do while), continue, break, jump and type conversion. Week 2 Arrays, Bitwise and log
1 min read
Java Collection Tutorial Java Collection Framework is unlikely any group of individual objects which are represented as a single unit be it of any type is known as the collection of objects. Earlier in Java, there was no such thing defined which holds true for it so there arises a need in the next versions of any such conce
15+ min read
Java Source File Structure Java source file structure describes that the Java source code file must follow a schema or structure. In this article, we will see some of the important guidelines that a Java program must follow. Â Â Â A Java program has the following structure: Â 1. package statements: A package in Java is a mechani
6 min read
Stream In Java Stream was introduced in Java 8, the Stream API is used to process collections of objects. A stream in Java is a sequence of objects that supports various methods that can be pipelined to produce the desired result. Use of Stream in JavaThe uses of Stream in Java are mentioned below:Stream API is a
7 min read
Java Collections Coding Practice Problems Java Collections provides dynamic and efficient data structures for handling and processing data. This collection of Java practice problems covers fundamental concepts of ArrayLists, LinkedLists, Stacks, Queues, Deques, PriorityQueues, HashMaps, and TreeSets, helping you master data manipulation, se
2 min read
Abstract Syntax Tree (AST) in Java Abstract Syntax Tree is a kind of tree representation of the abstract syntactic structure of source code written in a programming language. Each node of the tree denotes a construct occurring in the source code. There is numerous importance of AST with application in compilers as abstract syntax tre
5 min read