Concurrency Utilities
Creating and managing threads manually is difficult and error-prone. The Executor Framework (introduced in Java 5) separates task creation from execution.
ExecutorService
Instead of new Thread(task).start(), you use an Executor to run
tasks.
ExecutorService executor = Executors.newFixedThreadPool(10);
executor.execute(new RunnableTask());
executor.shutdown();
Thread Pools
Creating a new thread is expensive. A Thread Pool reuses a fixed number of threads to execute many tasks.
newFixedThreadPool(n): Reuses a fixed set of threads.newCachedThreadPool(): Creates new threads as needed, but reuses them if available.
Callable vs Runnable
Runnable doesn't return a value. Callable does!
Future<Integer> future = executor.submit(callableTask);
Integer result = future.get(); // Blocks until result is ready
Full Example
We will create a pool of 2 threads to execute 5 tasks.
Output
Click Run to execute your code
Summary
- Use ExecutorService instead of managing threads manually.
- Use Callable if you need a result from the thread.
- Always call
shutdown()to stop the executor.
Enjoying these tutorials?