Sobes.tech
Middle

What is ExecutorService in Java?

sobes.tech AI

Answer from AI

ExecutorService is a high-level alternative to manual thread management. It provides mechanisms for managing a thread pool and submitting tasks (implementing Runnable or Callable) for execution. This simplifies asynchronous task execution, thread lifecycle management, and controlling their number, avoiding the inefficiency of creating a new thread for each task.

Main advantages:

  • Thread lifecycle management: ExecutorService handles thread creation, start, and shutdown.
  • Number of threads: Allows configuring a fixed or dynamic number of threads in the pool.
  • Task queue: Tasks that cannot be executed immediately due to limited pool threads are placed in a queue.
  • Result handling: You can obtain task execution results using Future.

Interfaces and classes:

  • Executor: The basic interface providing the execute(Runnable) method.
  • ExecutorService: Extends Executor, adding methods for managing the pool's lifecycle (shutdown(), awaitTermination()) and accepting result-returning tasks (submit(Callable), submit(Runnable, T), invokeAll, invokeAny).
  • ScheduledExecutorService: Extends ExecutorService, adding scheduling capabilities for delayed or scheduled task execution.
  • Executors: A utility class providing factory methods for creating standard ExecutorService implementations.

Example of creation and usage:

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

// Create a thread pool with a fixed number of threads
ExecutorService executor = Executors.newFixedThreadPool(5);

// Submit a task for execution
executor.execute(() -> {
    // Code to run in a separate thread
    System.out.println("Task is running in thread: " + Thread.currentThread().getName());
});

// Another way to submit a task that returns a result (not shown in this example)
// Future<?> future = executor.submit(() -> { ... });

// Shutdown the ExecutorService
executor.shutdown();

// Wait for all tasks to complete in the pool (optional)
try {
    executor.awaitTermination(60, TimeUnit.SECONDS);
} catch (InterruptedException e) {
    e.printStackTrace();
}

System.out.println("ExecutorService has shut down.");