I have a piece of Java code that uses ExecutorService. I need to convert this code to Kotlin using coroutines. I tried using GlobalScope.launch() which did work but very differently. In Java code there is EXECUTOR_SERVICE.shutdown() and EXECUTOR_SERVICE.awaitTermination to determine when all the tasks are completed. What would be the closest implementation to this in Kotlin?
Java code:
final ExecutorService EXECUTOR_SERVICE =
Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
for (int d = MIN_DEPTH; d <= maxDepth; d += 2) {
final int depth = d;
EXECUTOR_SERVICE.execute(() -> {
int check = 0;
final int iterations = 1 << (maxDepth - depth + MIN_DEPTH);
for (int i = 1; i <= iterations; ++i) {
final TreeNode treeNode1 = bottomUpTree(depth);
check += treeNode1.itemCheck();
}
results[(depth - MIN_DEPTH) / 2] =
iterations + "\t trees of depth " + depth + "\t check: " + check;
});
}
EXECUTOR_SERVICE.shutdown();
EXECUTOR_SERVICE.awaitTermination(120L, TimeUnit.SECONDS);