Sobes.tech
Junior — Middle

Can you explain what ExecutorService is and how it is used to manage threads?

sobes.tech AI

Answer from AI

ExecutorService is an interface in Java that simplifies thread management by allowing asynchronous tasks to be run without directly creating and managing Thread objects.

It provides a thread pool where tasks (Runnable or Callable) can be submitted, and the ExecutorService itself manages their execution, thread lifecycle, and resource optimization.

Example usage:

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

public class Example {
    public static void main(String[] args) {
        ExecutorService executor = Executors.newFixedThreadPool(3); // pool of 3 threads

        for (int i = 0; i < 5; i++) {
            int taskId = i;
            executor.submit(() -> {
                System.out.println("Executing task " + taskId + " in thread " + Thread.currentThread().getName());
            });
        }

        executor.shutdown(); // shutdown after tasks are completed
    }
}

Thus, ExecutorService helps manage multithreading efficiently, avoiding the creation of excessive threads and simplifying the code.

Can you explain what ExecutorService is and how it is… - sobes.tech