Enjoying this Java & Concurrency tutorial?
Subscribe to Ram N Java on YouTubeIntroduction
Creating a new operating system thread for every incoming task in Java incurs significant memory and CPU overhead. A Thread Pool solves this problem by maintaining a pool of pre-created, reusable worker threads that execute tasks asynchronously from a blocking queue.
In this guide, you will learn how the ThreadPoolExecutor and the java.util.concurrent.Executors framework simplify multithreading, optimize system resource utilization, and improve application throughput.
1. Create a Runnable Task
Define a task by implementing the Runnable interface to represent the work to be executed by worker threads:
public class WorkerTask implements Runnable {
private final String taskName;
public WorkerTask(String taskName) {
this.taskName = taskName;
}
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + " executing " + taskName);
try {
Thread.sleep(1000); // Simulate work
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
System.out.println(Thread.currentThread().getName() + " completed " + taskName);
}
}
2. Initialize and Submit Tasks to ExecutorService
Create a fixed-size thread pool using the Executors factory class and submit multiple tasks for execution:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ThreadPoolDemo {
public static void main(String[] args) {
// Create a thread pool with 3 worker threads
ExecutorService executor = Executors.newFixedThreadPool(3);
// Submit 6 tasks to the pool
for (int i = 1; i <= 6; i++) {
executor.execute(new WorkerTask("Task-" + i));
}
// Shut down the executor gracefully after completion
executor.shutdown();
}
}
3. Key Advantages of Using Thread Pools
- Resource Management: Prevents system degradation caused by creating too many threads simultaneously.
- Better Performance: Eliminates thread creation and teardown latency by reusing existing threads.
- Task Queueing: Safely buffers excess tasks in internal blocking queues until threads become available.
No comments:
Post a Comment