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.
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
}
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?