Which of the following is true about the ExecutorService in Java?

Java MCQ: Which of the following is true about the ExecutorService in Java?

a) It allows for direct management of threads
b) It is used for managing a pool of threads
c) It cannot return results from submitted tasks
d) It is a subclass of the Thread class

Answer:

b) It is used for managing a pool of threads

Explanation:

The ExecutorService in Java is used for managing a pool of threads. It provides a higher-level API for working with threads, abstracting away the complexity of managing individual threads directly. The ExecutorService allows you to submit tasks for execution, which are then managed by a pool of worker threads.

Here’s an example of using ExecutorService:

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ExecutorServiceExample {
    public static void main(String[] args) {
        ExecutorService executor = Executors.newFixedThreadPool(3);

        for (int i = 0; i < 5; i++) {
            executor.submit(() -> {
                System.out.println("Task executed by: " + Thread.currentThread().getName());
            });
        }

        executor.shutdown();
    }
}

In this example, an ExecutorService is created with a fixed thread pool of 3 threads. Five tasks are submitted to the executor, and each task prints the name of the thread executing it. The shutdown() method is called to gracefully shut down the executor after all tasks are completed.

ExecutorService is part of the java.util.concurrent package and provides methods for task submission (submit()), shutting down the executor (shutdown(), shutdownNow()), and managing task completion (awaitTermination()). It is widely used in concurrent applications to manage thread pools and efficiently handle asynchronous tasks.

Reference links:

https://www.rameshfadatare.com/learn-java-programming/
https://www.javaguides.net/p/java-tutorial-learn-java-programming.html

Leave a Comment

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

Scroll to Top