Skip to content

Instantly share code, notes, and snippets.

@michaelilyin
Created December 11, 2018 15:27
Show Gist options
  • Save michaelilyin/6ffc190bd8188f56c795fa5846c9bc38 to your computer and use it in GitHub Desktop.
Save michaelilyin/6ffc190bd8188f56c795fa5846c9bc38 to your computer and use it in GitHub Desktop.
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import java.util.concurrent.Executors
import java.util.concurrent.atomic.AtomicInteger
import kotlin.concurrent.thread
import kotlin.system.measureTimeMillis
val n = 100
val delay = 1000L
fun calcPool() {
val int = AtomicInteger(0)
val executor = Executors.newWorkStealingPool()
val jobs = List(n) {
executor.submit {
Thread.sleep(delay)
int.incrementAndGet()
}
}
jobs.forEach { it.get() }
println("Pool: ${int.get()}")
}
fun calcThreads() {
val int = AtomicInteger(0)
val jobs = List(n) {
thread {
Thread.sleep(delay)
int.incrementAndGet()
}
}
jobs.forEach { it.join() }
println("Threads: ${int.get()}")
}
fun calcCoroutines() = runBlocking {
val int = AtomicInteger(0)
val jobs = List(n) {
launch {
delay(delay)
int.incrementAndGet()
}
}
jobs.forEach { it.join() }
println("Coroutines: ${int.get()}")
}
fun main(args: Array<String>) {
val coroutinesTotal = measureTimeMillis {
calcCoroutines()
}
println("Time: $coroutinesTotal")
println()
val threadsTotal = measureTimeMillis {
calcThreads()
}
println("Time: $threadsTotal")
println()
val poolTotal = measureTimeMillis {
calcPool()
}
println("Time: $poolTotal")
println()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment