Saturday, October 17, 2020

Kotlin - Multi-Threading in parallel and wait until all threads finish.

I share example how to execute Multi-Threading in parallel on Kotlin, is very useful if you want send a lot process simultaneously, In java you can use parallel stream and exist a lot examples, but it's almost the same.

I use an ExecutorService to manage pools of threads.

import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit

fun main(args: Array<String>) {
println("Started.....!")

var listStr = arrayOf("test1", "test2", "test3",
"test4", "test5", "test6", "test7", "test8", "test9", "test10")

var es = Executors.newCachedThreadPool()

for (item in listStr) {
es.execute {
println("item -> $item")
}
}

es.shutdown()
var finished = es.awaitTermination(1, TimeUnit.MINUTES)
println("\\nFinished all threads $finished")

}


Run test: check test 3 execute after test 4 and test 2 execute after test 3. 



















References:
https://winterbe.com/posts/2015/04/07/java8-concurrency-tutorial-thread-executor-examples/
https://howtodoinjava.com/java/multi-threading/executorservice-invokeall/
https://crunchify.com/how-to-run-multiple-threads-concurrently-in-java-executorservice-approach/
https://stackoverflow.com/questions/7939257/wait-until-all-threads-finish-their-work-in-java

No comments:

Post a Comment

Creating REST APIs with OpenAPI, Spring Boot 3.3.3, Java 21, and Jakarta

 Introduction In today's software landscape, designing robust and scalable REST APIs is a crucial aspect of application development. Wit...