Home > OS >  ExecutorService analog in Kotlin
ExecutorService analog in Kotlin

Time:04-10

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);

CodePudding user response:

Kotlin does not tie thread pools to work completion, but your solution was already an accurate translation. You do not need to do anything special to wait for the tasks to complete; this is done automatically by launch and by every coroutine builder method as a result of structured concurrency.

I would write this as

val result : List<Int> = runBlocking {
  // you can specify a thread pool, but it looks like you should really use the default one
  (MIN_DEPTH..maxDepth step 2).map { depth ->
    async {
      val check = 0
      val iterations = 1 shl (maxDepth - depth   MIN_DEPTH)
      for (i in 0 until iterations) {
        check  = bottomUpTree(depth).itemCheck()
      }
      check
    }
   }.awaitAll()
}
  • Related