Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • 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
  • 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:
Java.util.concurrent.ExecutorService Interface with Examples
Next article icon

Java.util.concurrent.ExecutorService Interface with Examples

Last Updated : 13 May, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

The ExecutorService interface extends Executor by adding methods that help manage and control the execution of threads. It is defined in java.util.concurrent package. It defines methods that execute the threads that return results, a set of threads that determine the shutdown status. The ExecutorService interface is implemented in a utility class called Executors. It defines methods that provide an implementation of the ExecutorService interface and many other interfaces, with some default settings.

The class hierarchy is as follows: 

--> java.util.concurrent Package     --> Interface ExecutorService Class 

Note: ScheduledExecutorService is Implementing Sub-Interfaces and classes implemented are as follows:

  • AbstractExecutorService
  • ForkJoinPool
  • ScheduledThreadPoolExecutor
  • ThreadPoolExecutor

Methods in Executor Interface

MethodAction Performed
awaitTermination()Waits for all the tasks to complete their execution after a shutdown request is found. It waits for the time specified by the timelimit argument
invokeAll()Executes all the tasks contained in the collection. The list of Future objects is returned which contains the status and return values of the various tasks
 invokeAny()Executes all the tasks contained in the collection. On completion of any single task it returns its result and all the other tasks are canceled.
isShutdown()Tells whether the invoking executor is shut down or not. Returns true if shutdown otherwise returns false
isTerminated()Checks if all the tasks have been completed post-shutdown. Return true if completed, otherwise returns false.
shutdown()Causes all the currently executing tasks to terminate after completion in the order in which they were started and rejects any new incoming tasks.
shutdownNow()Forcefully terminates all the tasks, regardless of their current state i.e running, waiting, or ready. The lists of tasks were in a ready state in return.
submit()Adds a task that returns a result to the list of executing tasks for execution. It returns a Future object which returns the result of the task after completion

Implementation: Executors 

Java
// Java Program to Demonstrate ExecutorService Interface  // Importing required classes import java.util.concurrent.*;  // Class // Main class public class SimpleExecutor {      // Main driver method     public static void main(String[] args)     {         // Creating objects of CountDownLatch class         CountDownLatch cd1 = new CountDownLatch(5);         CountDownLatch cd2 = new CountDownLatch(5);         CountDownLatch cd3 = new CountDownLatch(5);         CountDownLatch cd4 = new CountDownLatch(5);          // Creating objects of ExecutorService class         ExecutorService es             = Executors.newFixedThreadPool(2);          // Display message only for better readability         System.out.println("Starting");          // Executing the tasks          es.execute(new MyThread(cd1, "A"));         es.execute(new MyThread(cd2, "B"));         es.execute(new MyThread(cd3, "C"));         es.execute(new MyThread(cd4, "D"));          // Try block to check for exceptions         try {              // Waiting for tasks to complete             cd1.await();             cd2.await();             cd3.await();             cd4.await();         }          // Catch block to handle exceptions         catch (InterruptedException e) {                        System.out.println(e);         }          // Making all current executing threads to terminate         es.shutdown();          // Display message only for better readability         System.out.println("Done");     } }  // Class 2 // Helper class class MyThread implements Runnable {      // Class data members     String name;     CountDownLatch latch;      // Constructor     MyThread(CountDownLatch latch, String name)     {          // this keyword refers to current instance itself         this.name = name;         this.latch = latch;          new Thread(this);     }      // Method     // Called automatically when thread is started     public void run()     {          for (int i = 0; i < 5; i++) {             System.out.println(name + ": " + i);             latch.countDown();         }     } } 

Output:

 

Next Article
Java.util.concurrent.ExecutorService Interface with Examples

C

CharchitKapoor
Improve
Article Tags :
  • Java
  • Java - util package
  • Java-concurrent-package
Practice Tags :
  • Java

Similar Reads

    Java.util.concurrent.Executor interface with Examples
    The concurrent API in Java provides a feature known as an executor that initiates and controls the execution of threads. As such, an executor offers an alternative to managing threads using the thread class. At the core of an executor is the Executor interface. It refers to the objects that execute
    1 min read
    Java.util.concurrent.Exchanger class with Examples
    Exchanger is the most interesting synchronization class of Java. It facilitates the exchange of elements between a pair of threads by creating a synchronization point. It simplifies the exchange of data between two threads. Its operation is simple: it simply waits until two separate threads call its
    3 min read
    Java.util.concurrent.Phaser class in Java with Examples
    Phaser's primary purpose is to enable synchronization of threads that represent one or more phases of activity. It lets us define a synchronization object that waits until a specific phase has been completed. It then advances to the next phase until that phase concludes. It can also be used to synch
    7 min read
    ConcurrentMap Interface in Java
    The ConcurrentMap Interface is part of the Java Collections Framework and was introduced in JDK 1.5. It is designed for thread-safe concurrent access to its entries without compromising the consistency of the map. The interface resides in the java.util.concurrent package and extends the Map interfac
    9 min read
    Java.util.concurrent.RecursiveTask class in Java with Examples
    RecursiveTask is an abstract class encapsulates a task that returns a result. It is a subclass of ForkJoinTask. The RecursiveTask class is extended to create a task that has a particular return type. The code that represents the computational portion of the task is kept within the compute() method o
    2 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