How do you test code that uses ThreadPoolExecutor?

Testing code that utilizes a ThreadPoolExecutor is important for ensuring that multithreaded applications behave as expected. Below is a simple example demonstrating how to create a unit test for code that employs ThreadPoolExecutor. We'll use the JUnit framework for our testing.

Example of Testing ThreadPoolExecutor

import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class ThreadPoolExecutorTest { private ExecutorService executor; private CountDownLatch latch; @Before public void setUp() { executor = Executors.newFixedThreadPool(2); } @After public void tearDown() { if (executor != null) { executor.shutdown(); } } @Test public void testThreadExecution() throws InterruptedException { latch = new CountDownLatch(2); Runnable task1 = () -> { // Simulating some work System.out.println("Task 1 is running"); latch.countDown(); }; Runnable task2 = () -> { // Simulating some work System.out.println("Task 2 is running"); latch.countDown(); }; executor.execute(task1); executor.execute(task2); latch.await(); // Wait for both tasks to finish Assert.assertEquals(0, latch.getCount()); // Ensure both tasks completed } }

ThreadPoolExecutor JUnit Concurrent Testing Multithreading Java Unit Testing