Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
Stream In Java
Next article icon

Structured Concurrency in Java

Last Updated : 14 May, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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:

  1. ExecutorService and CompletableFuture
  2. 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();     } } 

Output
Task 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();     } } 

Output
Task 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.


Next Article
Stream In Java

S

sanketnagare
Improve
Article Tags :
  • Java
  • Java Concurrency
Practice Tags :
  • Java

Similar Reads

  • 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
  • ConcurrentLinkedQueue in Java
    In Java, the ConcurrentLinkedQueue is the part of the java.util.concurrent package and implements a FIFO(First-In-First-Out) queue. It is a thread-safe, non-blocking, and scalable queue designed for use in highly concurrent environments. The queue uses a lock-free algorithm, ensuring that multiple t
    8 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
  • B-Tree in Java
    A B-tree is a self-balanced tree data structure that will maintain the sorted data and allow for operations such as insertion, deletion and search operations. B-tree is particularly well-suited for systems that need to perform disk-based operations and it minimizes the number of disk accesses requir
    6 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
  • Stack Class in Java
    The Java Collection framework provides a Stack class, which implements a Stack data structure. The class is based on the basic principle of LIFO (last-in-first-out). Besides the basic push and pop operations, the class also provides three more functions, such as empty, search, and peek. The Stack cl
    12 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
  • Generic MultiMap in java
    In Java, a map is an interface. The map exists in the package java.util. The data is stored as a Key-Value pair in the map, which is a collection of keys and values. HashMap, TreeMap, and LinkedHashMap are the tools used to implement it. Every class has unique characteristics. It does not maintain t
    4 min read
  • Cohesion in Java
    Cohesion in Java is the Object-Oriented principle most closely associated with making sure that a class is designed with a single, well-focused purpose. In object-oriented design, cohesion refers to how a single class is designed. Note: The more focused a class is, the more is the cohesiveness of th
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences