What are best practices for working with ThreadPoolExecutor?

Best practices for working with ThreadPoolExecutor in Java to improve performance and resource management in concurrent applications.

ThreadPoolExecutor, Java concurrency, best practices, performance optimization, resource management

<?php // Example of using ThreadPoolExecutor in Java import java.util.concurrent.Executors; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; public class ThreadPoolExecutorExample { public static void main(String[] args) { // Create a ThreadPoolExecutor with a fixed number of threads ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(5); // Submit tasks to the executor for (int i = 0; i < 10; i++) { executor.submit(new RunnableTask(i)); } // Shutdown the executor gracefully executor.shutdown(); try { if (!executor.awaitTermination(60, TimeUnit.SECONDS)) { executor.shutdownNow(); } } catch (InterruptedException e) { executor.shutdownNow(); } } } class RunnableTask implements Runnable { private final int taskId; public RunnableTask(int taskId) { this.taskId = taskId; } @Override public void run() { System.out.println("Executing task ID: " + taskId); try { Thread.sleep(2000); // Simulate task workload } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } } ?>

ThreadPoolExecutor Java concurrency best practices performance optimization resource management