Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is Java Executor Framework?
2.1.
Executor Interface
2.2.
ThreadPoolExecutor
2.3.
ScheduledExecutorService
2.4.
Executors Utility Class
3.
Types of Executor Framework
3.1.
1. SingleThreadExecutor
3.2.
2. FixedThreadPool(n)
3.3.
3. CachedThreadPool
3.4.
4. ScheduledExecutor
4.
Implementing a Simple Executor Framework in Java
4.1.
Implementation
4.2.
Java Code
5.
Frequently Asked Questions
5.1.
What are the Executor interfaces framework?
5.2.
What is an example of an Executor in Java?
5.3.
Why is Executor framework better?
5.4.
What is the Executor framework in REST API?
6.
Conclusion
Last Updated: Mar 27, 2024
Easy

Executor Framework in Java

Author Gaurav Gandhi
0 upvote
Master Power BI using Netflix Data
Speaker
Ashwin Goyal
Product @
18 Jun, 2024 @ 01:30 PM

Introduction

Java's Executor Framework is a cornerstone of concurrent programming, offering a sophisticated platform for executing asynchronous tasks. It simplifies thread management, allowing developers to focus on implementing business logic rather than the intricacies of thread life cycles.

executor framework in java

In this blog, we will learn about the executor framework in Java. We will discuss types of executor frameworks and will later implement a simple executor framework in Java. 

What is Java Executor Framework?

The Executor Framework is part of the java.util.concurrent package and provides a set of interfaces and classes for managing thread pools and executing asynchronous tasks.

Executor Interface

The Executor interface is the simplest abstraction in the framework, which provides an execute(Runnable command) method to run tasks asynchronously.

ThreadPoolExecutor

ThreadPoolExecutor is an implementation of ExecutorService, managing a pool of threads and executing tasks with various configurable parameters.

ScheduledExecutorService

ScheduledExecutorService is used for scheduling tasks to run after a specified delay or at regular intervals, ideal for periodic task execution.

Executors Utility Class

The Executors utility class contains factory methods for creating pre-configured executor services, such as SingleThreadExecutor, FixedThreadPool, CachedThreadPool, and ScheduledThreadPoolExecutor.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Types of Executor Framework

We have four types of executor framework: 

Types of Executor Framework

1. SingleThreadExecutor

A SingleThreadExecutor manages a single thread for executing tasks sequentially.

Sequential Execution

Tasks are executed one after another, ensuring a predictable processing order.

Worker Thread

A single thread executes all tasks, avoiding the need for multiple threads and synchronization.

No Parallelism

Tasks are not executed in parallel, simplifying the programming model.

Syntax and Example

ExecutorService executor = Executors.newSingleThreadExecutor();
executor.execute(() -> System.out.println("Executed by: " + Thread.currentThread().getName()));
executor.shutdown();

Output Explanation:

The output will display the message "Executed by: [thread name]", indicating the single thread managed by the SingleThreadExecutor.

2. FixedThreadPool(n)

A FixedThreadPool maintains a fixed number of threads, providing a controlled environment for concurrent task execution.

Syntax and Example

int n = 5; // Number of threads
ExecutorService executor = Executors.newFixedThreadPool(n);
for (int i = 0; i < 10; i++) {
    int taskId = i;
    executor.execute(() -> System.out.println("Task " + taskId + " executed by: " + Thread.currentThread().getName()));
}
executor.shutdown();

Output Explanation:

Each task's output indicates the task ID and the thread executing it, demonstrating how tasks are distributed among the fixed number of threads.

3. CachedThreadPool

A CachedThreadPool dynamically adjusts the thread count based on the workload, suitable for applications with fluctuating task loads.

Syntax and Example

ExecutorService executor = Executors.newCachedThreadPool();
for (int i = 0; i < 10; i++) {
    executor.execute(() -> {
        try {
            Thread.sleep(1000); // Simulate task time
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
        System.out.println("Task completed by: " + Thread.currentThread().getName());
    });
}

executor.shutdown();

Output Explanation:

The output will show "Task completed by: [thread name]" for each task, illustrating the dynamic allocation and reuse of threads.

4. ScheduledExecutor

ScheduledExecutor is designed for tasks that need to run on a schedule, either after a fixed delay or periodically.

Syntax and Example

ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
executor.schedule(() -> System.out.println("Task executed after delay"), 5, TimeUnit.SECONDS);
executor.shutdown();

Output Explanation:

The output will display "Task executed after delay" after a 5-second delay, showcasing the scheduling capability of the ScheduledExecutor.

Implementing a Simple Executor Framework in Java

We'll demonstrate a FixedThreadPool executor with three threads to concurrently execute tasks.

Implementation

  • Java Code

Java Code

import java.util.concurrent.ExecutorService;

import java.util.concurrent.Executors;

public class SimpleExecutorFrameworkExample {

public static void main(String[] args) {

ExecutorService executor = Executors.newFixedThreadPool(3);

for (int i = 1; i <= 3; i++) {

final int taskId = i;

executor.execute(() -> System.out.println("Task " + taskId + " running on thread: " + Thread.currentThread().getName()));

}

executor.shutdown();

}

}

Output

output

The output will show each task being executed concurrently by different threads from the pool, such as "Task 1 running on thread: pool-1-thread-1". This demonstrates the concurrent execution of tasks within a controlled thread environment.

Frequently Asked Questions

What are the Executor interfaces framework?

In Java, the Executor framework provides interfaces like Executor, ExecutorService, and ScheduledExecutorService for managing concurrent tasks.

What is an example of an Executor in Java?

ThreadPoolExecutor is an example of an Executor in Java, managing and executing threads efficiently.

Why is Executor framework better?

Enhances thread management, simplifies task execution, and provides better control over concurrency compared to managing threads manually.

What is the Executor framework in REST API?

The Executor framework in the context of a REST API typically refers to managing asynchronous tasks or background processes efficiently.

Conclusion

The Executor Framework in Java is a powerful tool for managing concurrent tasks. It provides a high level of abstraction for thread management, allowing developers to focus on implementing business logic rather than the intricacies of thread lifecycle. By understanding and utilizing the different types of executors, developers can write more efficient, scalable, and maintainable concurrent applications.

You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. 

Also, check out some of the Guided Paths on topics such as Data Structure and AlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.

Live masterclass