Reputation: 1106
I am trying my first steps with Java 8 concurrency. In the code example below, an exception is thrown because the my tasks sleep 2 seconds. The shutdown function waits 5 seconds for termination. Therefore, only two loops are executed. Is there a dynamic solution to this instead of counting the max time the execution could take and adjusting the value of the awaitTermination()-method?
public class Application {
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(1);
IntStream.range(0, 10).forEach(i ->
executor.submit(() -> {
try {
TimeUnit.SECONDS.sleep(2);
System.out.println("Hello");
} catch (InterruptedException e) {
throw new IllegalStateException("Task interrupted", e);
}
})
);
shutdown(executor);
}
private static void shutdown(ExecutorService executor) {
try {
executor.shutdown();
executor.awaitTermination(5, TimeUnit.SECONDS);
} catch (InterruptedException e) {
System.err.println("tasks interrupted");
} finally {
if (!executor.isTerminated()) {
System.err.println("cancel non-finished tasks");
}
executor.shutdownNow();
}
}
Upvotes: 4
Views: 249
Reputation: 21883
Adding to what @AdamSkyWalker mentioned you can use a CountDownLatch as you already know the no of Threads (10 in this case).
public static void main(String[] args) throws Exception {
ExecutorService executor = Executors.newFixedThreadPool(1);
final CountDownLatch latch = new CountDownLatch(10);
IntStream.range(0, 10).forEach(i ->
executor.submit(() -> {
try {
TimeUnit.SECONDS.sleep(2);
System.out.println("Hello");
} catch (InterruptedException e) {
throw new IllegalStateException("Task interrupted", e);
} finally {
latch.countDown();
}
})
);
latch.await();
}
}
I wrote a post sometime back on comparing CountDownLatch
, Semaphore
and CyclicBarrier
which will be helpful for you.
Upvotes: 5