Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email
Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

Executor Framework in Java

Java Programming Language is widely used for the development of complex enterprise-level software. One of the features that java provides is multithreading. Java enables developers to write concurrent programs that can execute simultaneously at the same time. Java has its own multi-threading framework which is known as Java Executor Framework. Let us learn about the Executor Framework in Java in detail.

What is Executor Framework in Java?

Executor Framework in Java is defined as a bunch of components that are used for the management of worker threads in a more efficient manner. This Executor Framework in Java provides a high-level abstraction that simplifies the process of creating and managing threads in a Java program. It provides a set of classes and interfaces which enables the java developers in creating and managing the thread pools. This helps the developer to focus on the task logic, rather than on the management of the threads.

The Executor Framework in Java was introduced in Java5 and is a part of java.util.concurrent Package.

Working of Executor Framework in Java

The Executor Framework in Java works by separating the task submission and execution logic from the Thread Management section. With the help of the Executor Framework in Java, developers can now submit the tasks to the Executor Instance instead of creating the threads manually. The Executor Instance mentioned here is responsible for managing the threads that are executing the tasks.

The Executor interface in Java defines a single method, execute(Runnable task), which accepts a Runnable instance representing the task to be executed. When a task is submitted to an Executor instance, the framework determines which thread should execute the task, and schedules it for execution.

Types of Executor Framework in Java

The Executor Framework in Java provides different types of executors for assisting Java developers. Here are some commonly used Executors in Java.

  • SingleThreadExecutor
  • FixedThreadPool(n)
  • CachedThreadPool
  • ScheduledExecutor

Now let us discuss all of these Executors in detail along with with their syntax.

  • Single Thread Executor in Java
    This SingleThreadExecutor in Java is an executor that has only one single thread. This type of executor is used when we need to execute tasks in a sequential manner.

    Note: If there is a case that the current thread dies due to some error, a new thread will be created and all remaining tasks will be executed in the new thread.

    Syntax of Single Thread Executor in Java
    Here is how we declare a SingleThreadExecutor in Java.

    ExecutorService executor = Executors.newSingleThreadExecutor();
  • FixedThreadPool(n) in Java
    This type of Executor in Java has a thread pool of a fixed number of threads. It means that the task submitted to this executor is executed by the n threads. Here n denotes the total number of threads that can be supported by the processor. These remaining tasks are stored in the LinkedBlockingQueue.

    Syntax of FixedThreadPool(n) in Java
    The syntax of FixedThreadPool Executor in Java is given below.

    ExecutorService executor = Executors.newFixedThreadPool(n);  
  • Cached Thread Pool in Java
    The CachedThreadPool Executor in Java is a special type of executor that is used to execute the short living parallel tasks. Like FixedThreadPool, the CacjedThreadPool does not have a fixed number of threads. This executor used the Synchronous Queue.

    Syntax of Cached Thread Pool in Java
    The syntax for the CachedThreadPool in Java is given below.

    ExecutorService executor = Executors.newCachedThreadPool();  
  • Scheduled Executor in Java
    The ScheduledExecutor in Java is used when we need to run a certain task at regular intervals of time. This Executor is also used when we need to delay a task. It is based on ScheduledExecutorService.

    Syntax of Scheduled Executor in Java
    Here is how we declare a ScheduledExecutor in Java.

    ScheduledExecutorService scheduledExecService = Executors.newScheduledThreadPool(1);  

    The tasks in this executor are processed using the following two methods.

    • scheduledAtFixedRate: This method executes the task with a fixed interval and does not depend on when the previous task ended.

      scheduledExecService.scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit)
    • scheduleWithFixedDelay: This method starts the delay countdown only after the completion of the current task.

      scheduledExecService.scheduleWithFixedDelay(Runnable command, long initialDelay, long period, TimeUnit unit)

Example of Executor Framework in Java

Let us see an example to learn how to use the Executor Framework in Java.

import java.util.concurrent.*;

class Task implements Callable<String> {
    private String message;

    public Task(String message){
        this.message = message;
    }

    public String call() throws Exception{
        return "Hiiii " + message + "!";
    }
}

class PrepBytes{
    public static void main(String[] args){
        Task task = new Task("PrepBuddy");
        
        ExecutorService executorService = Executors.newFixedThreadPool(4);
        Future<String> result = executorService.submit(task);

        try {
            System.out.println(result.get());
        } catch (InterruptedException | ExecutionException e) {
            System.out.println("Error occurred while executing the submitted task");
            e.printStackTrace();
        }
        executorService.shutdown();
    }
}

Output:

Hiiii PrepBuddy!

Explanation:
In the above code, declared a class “Task” which implements the Callable Interface. In the main Class, we have instantiated an object of the “Task” class. We have declared an Executor of type FixedThreadPool of size 4. Next, we used the general try-catch block to execute the commands.

Conclusion
The Executor framework is a powerful tool for concurrent programming in Java, providing a simple and efficient way to manage threads and execute tasks concurrently. The framework abstracts the details of thread creation and management, making it easier for developers to focus on task logic, rather than thread management. In this article, we have learned about the Executor Framework in Java and different types of Executors with their syntax.

Frequently Asked Questions(FAQs)

Here are some Frequently Asked Questions related to Executor Framework in Java.

Ques 1. What is a thread pool?
Ans. A thread pool is a collection of threads that are created to execute a set of tasks. The threads in the pool are created in advance and reused to execute multiple tasks, reducing the overhead of thread creation.

Ques 2. How does the Executor framework create a thread pool?
Ans. The Executor framework creates a thread pool using the ThreadPoolExecutor class. The thread pool is created with a fixed number of threads or a dynamically adjustable number of threads, depending on the type of executor used.

Ques 3. What is the difference between a fixed thread pool and a cached thread pool?
Ans. A fixed thread pool has a fixed number of threads that are created when the thread pool is created, while a cached thread pool creates threads on demand and terminates idle threads after a certain period of time.

Ques 4. What is the difference between a Callable and a Runnable in Java?
Ans. A Callable is similar to a Runnable, but it returns a result and can throw an exception.

Leave a Reply

Your email address will not be published. Required fields are marked *