← Back to Chapters

Executor Framework

⚙️ Executor Framework

? Quick Overview

The Executor Framework in Java provides a high-level API for managing and executing threads. Instead of manually creating and controlling threads, developers submit tasks to an executor service which handles thread creation, scheduling, and lifecycle management.

? Key Concepts

  • Executor – Simple interface for executing tasks
  • ExecutorService – Manages task lifecycle and thread pool
  • Thread Pool – Reusable group of worker threads
  • Callable – Task that returns a result
  • Future – Represents the result of an async computation

? Syntax / Theory

The framework is available in the java.util.concurrent package and supports different types of thread pools such as fixed, cached, and single-thread executors.

? Code Example(s)

? View Code Example
// Creating a fixed thread pool with 2 threads
ExecutorService executor = Executors.newFixedThreadPool(2);

// Submitting a simple Runnable task
executor.submit(() -> {
System.out.println("Task executed by: " + Thread.currentThread().getName());
});

// Shutting down the executor service
executor.shutdown();
? View Code Example
// Callable task that returns a value
Callable task = () -> {
return 10 + 20;
};

// Single thread executor
ExecutorService service = Executors.newSingleThreadExecutor();

// Submitting Callable and getting Future
Future result = service.submit(task);

// Fetching result from Future
System.out.println(result.get());

service.shutdown();

⚡ Interactive Thread Pool Simulator

Visualize how a Fixed Thread Pool (Size: 3) processes a queue of tasks.

Active Threads: 0/3

BlockingQueue (Waiting)

 

ThreadPool (Executing)

 

? Live Output / Explanation

Explanation

The executor picks an available thread from the pool and runs the submitted task. For Callable, the result is returned using a Future object, allowing asynchronous processing.

✅ Tips & Best Practices

  • Always shut down executor services to free resources
  • Prefer thread pools over manual thread creation
  • Use Callable when a result is required
  • Choose the correct executor type based on workload

? Try It Yourself

  • Create a fixed thread pool with 3 threads
  • Submit multiple Runnable tasks
  • Use Future to check task completion