java concurrency understanding thread pool and executors
In Java, a thread pool is a group of pre-initialized threads that are available to perform a set of tasks. Instead of creating a new thread for each task, a thread pool allows us to reuse threads from a pool of threads, which reduces the overhead of thread creation and context switching.
Java provides the java.util.concurrent.Executor
interface and its sub-interfaces ExecutorService
and ScheduledExecutorService
to work with thread pools. Here's an example of how to create and use a thread pool with the ExecutorService
interface:
import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class ThreadPoolExample { public static void main(String[] args) { // Create a thread pool with 2 threads ExecutorService executor = Executors.newFixedThreadPool(2); // Submit two tasks to the thread pool executor.submit(() -> { System.out.println("Task 1 executed by thread: " + Thread.currentThread().getName()); }); executor.submit(() -> { System.out.println("Task 2 executed by thread: " + Thread.currentThread().getName()); }); // Shutdown the thread pool executor.shutdown(); } }
In this example, we create a thread pool with 2 threads using the newFixedThreadPool()
method of the Executors
class. We then submit two tasks to the thread pool using the submit()
method of the ExecutorService
. Each task is a lambda expression that prints a message to the console along with the name of the thread that executes the task. Finally, we call the shutdown()
method of the ExecutorService
to terminate the thread pool.
Java also provides other types of thread pools such as CachedThreadPool
and SingleThreadPool
. The CachedThreadPool
creates a new thread for each task and can reuse previously created threads if they are available. The SingleThreadPool
creates a single thread to execute tasks sequentially.
In addition to the ExecutorService
, Java also provides the ScheduledExecutorService
interface to schedule tasks to be executed after a delay or periodically at a fixed rate or with a fixed delay between each execution.
Using thread pools with the Java concurrency APIs can help improve the performance of multi-threaded applications by reducing the overhead of thread creation and context switching, as well as providing more control over the execution of tasks.