3

I've been trying to find an explanation on why this works in kotlin:

(1..100).map {
    launch {
        System.out.println("Hello from on ${Thread.currentThread().name}")
        delay(100)
    }
}.forEach { it.join() }

In java this would:

  1. start thread 1
  2. join thread 1 - and block here, never starting more than 1 thread.

In kotlin this process on multiple threads in parallel.

Why does this work?

s1m0nw1
  • 76,759
  • 17
  • 167
  • 196
neuron
  • 1,224
  • 12
  • 14

1 Answers1

3

The map call terminates before forEach, thus every single launch will be called before the first join (inside forEach). These collection operations don’t work like Java‘s Streams. Read this answer for further information.

In Kotlin it’s like this:

  • launch coroutine 1-100
  • join coroutine 1-100
s1m0nw1
  • 76,759
  • 17
  • 167
  • 196
  • (1..100).asSequence() if you want it to be lazy like java streams. Nvm it's in the linked answer (: – Cyril Jan 05 '18 at 12:04