Reputation: 6290
I have a Threadpool, please see the code below. What I want now is that before the asserEquals statement it is waited until all jobs finished. How can this be achieved? awaitTermination() only works if shutdown is already called but that is not what I want.
private volatile int i = 0;
@Test
public void threadPoolTest() throws InterruptedException {
ExecutorService threadPool = Executors.newFixedThreadPool(8);
threadPool.submit(new Runnable() {
public void run() {
i++;
}
});
threadPool.submit(new Runnable() {
public void run() {
i++;
}
});
assertEquals(2,i);
threadPool .shutdown();
}
Upvotes: 0
Views: 1479
Reputation: 11022
try using a CountDownLatch : it's a concurrency barrier which can await N tasks like a counter :
@Test
public void threadPoolTest() throws InterruptedException {
ExecutorService threadPool = Executors.newFixedThreadPool(8);
final CountDownLatch latch = new CountDownLatch(2);
threadPool.submit(new Runnable() {
public void run() {
i++;
latch.countDown();
}
});
threadPool.submit(new Runnable() {
public void run() {
i++;
latch.countDown();
}
});
latch.await();
assertEquals(2,i);
threadPool .shutdown();
}
Upvotes: 4
Reputation: 19237
// tell the threadpool it shouldn't accept new tasks:
threadPool.shutdown();
// and wait until the already submitted tasks finish:
try {
threadPool.awaitTermination(...);
assertEquals(2,i);
} catch(InterruptedException e) {
assertTrue(false); // shouldn't get here only if timeouts
}
If you don't want to shutdown the pool beforehand then you might use a CountDownLatch and count until the threads finish. The problem with it is that theoretically some other thread can add to the pool even after you started to "count down", that's why usually you shutdown so no other jobs can be added later.
Upvotes: 1