Sobes.tech
Middle

What is the difference between the Executor interface and ExecutorService?

sobes.tech AI

Answer from AI

Executor is a basic interface that defines the execute(Runnable command) method for running tasks.

ExecutorService extends Executor and adds more powerful capabilities for managing tasks and the lifecycle of thread pools:

  • Allows submitting tasks and obtaining a Future to track the result.
  • Supports methods for shutdown, such as shutdown() and shutdownNow().
  • Enables executing tasks with timeouts, waiting for completion, etc.

Example:

Executor executor = Executors.newSingleThreadExecutor();
executor.execute(() -> System.out.println("Task executed"));

ExecutorService service = Executors.newFixedThreadPool(2);
Future<String> future = service.submit(() -> "Result");
String result = future.get();
service.shutdown();

Thus, Executor is a simple interface for running tasks, while ExecutorService is an extended service with management and control over execution.