YouTip LogoYouTip

Java Executorservice Class

ExecutorService is a core interface in Java concurrent programming, belonging to the `java.util.concurrent` package. ExecutorService provides a more advanced way of managing threads, allowing developers to efficiently execute asynchronous tasks without manually creating and managing threads. The main functions of ExecutorService include: * **Thread Pool Management**: Automatically manages the lifecycle of threads, reducing the overhead of thread creation and destruction. * **Task Scheduling**: Supports submitting `Runnable` or `Callable` tasks and returns a `Future` object to track the task's execution status. * **Resource Optimization**: Reuses threads through thread pools, improving system performance. * * * ## Core Methods of ExecutorService ExecutorService offers various methods for submitting, managing, and controlling task execution. Here are some key methods: ### `submit()` Used to submit a task (either `Runnable` or `Callable`) and return a `Future` object, allowing you to check whether the task has completed or retrieve its result. ## Example ExecutorService executor = Executors.newFixedThreadPool(2); Future future = executor.submit(() -> { System.out.println("Task is running"); }); ### `execute()` Only used to submit `Runnable` tasks, without returning any result. ## Example executor.execute(() -> { System.out.println("Task executed"); }); ### `shutdown()` Gracefully shuts down the thread pool, no longer accepting new tasks but waiting for already submitted tasks to complete. ## Example executor.shutdown(); ### `shutdownNow()` Immediately shuts down the thread pool, attempts to interrupt all currently executing tasks, and returns a list of unexecuted tasks. ## Example List notExecutedTasks = executor.shutdownNow(); ### `awaitTermination()` Waits for the thread pool to shut down until all tasks have completed or a timeout occurs. ## Example executor.awaitTermination(10, TimeUnit.SECONDS); * * * ## How to Create an ExecutorService Java provides the `Executors` utility class to create different types of thread pools: ### `newFixedThreadPool(int nThreads)` Creates a fixed-size thread pool, suitable for tasks with stable workloads. ## Example ExecutorService fixedThreadPool = Executors.newFixedThreadPool(4); ### `newCachedThreadPool()` Creates a cached thread pool, ideal for short-lived asynchronous tasks. ## Example ExecutorService cachedThreadPool = Executors.newCachedThreadPool(); ### `newSingleThreadExecutor()` Creates a single-threaded thread pool, suitable for tasks that need to be executed sequentially. ## Example ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor(); ### `newScheduledThreadPool(int corePoolSize)` Creates a thread pool that supports scheduled or periodic tasks. ## Example ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(2); * * * ## Usage Examples ### Submitting Runnable Tasks ## Example ExecutorService executor = Executors.newFixedThreadPool(2); executor.submit(() -> { System.out.println("Task 1 running"); }); executor.submit(() -> { System.out.println("Task 2 running"); }); executor.shutdown(); ### Submitting Callable Tasks and Retrieving Results ## Example ExecutorService executor = Executors.newFixedThreadPool(2); Future future = executor.submit(() -> { Thread.sleep(1000); return "Task completed"; }); try { String result = future.get(); // Blocks until the task completes System.out.println(result); } catch (Exception e) { e.printStackTrace(); } executor.shutdown(); * * * ## Best Practices 1. **Set an Appropriate Thread Pool Size**: * For CPU-bound tasks: `Number of threads = Number of CPU cores + 1` * For I/O-bound tasks: `Number of threads = Number of CPU cores Γ— 2` 2. **Avoid Memory Leaks**: * Ensure that `shutdown()` or `shutdownNow()` is called to properly close the thread pool. 3. **Handle Exceptions**: * Use `try-catch` blocks to capture exceptions within tasks, preventing unexpected thread termination. 4. **Use `Future` to Manage Tasks**: * Retrieve task results or check their status using `Future.get()`.
← Java Socket ClassJava Outputstream Class β†’