Skip to content

Instantly share code, notes, and snippets.

@denyago
Created October 17, 2024 12:41
Show Gist options
  • Save denyago/1cf8660eaa12c3d2700befea7812fdc9 to your computer and use it in GitHub Desktop.
Save denyago/1cf8660eaa12c3d2700befea7812fdc9 to your computer and use it in GitHub Desktop.
Comparison of Coroutine-based and JVM Virtual Thread -based approaches to building parallel running tasks.
package com.finmid
import kotlinx.coroutines.async
import kotlinx.coroutines.delay
import kotlinx.coroutines.runBlocking
import java.time.Instant
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors
import java.util.concurrent.Future
import java.util.concurrent.FutureTask
class SuspendRepo {
suspend fun findOne(): String {
delay(100L)
println("${Instant.now()}: After one")
return "Hello"
}
suspend fun findTwo(): String {
delay(100L)
println("${Instant.now()}: After two")
return "World"
}
}
class LoomRepo {
fun findOne(): String {
Thread.sleep(100L)
println("${Instant.now()}: After one")
return "Hello"
}
fun findTwo(): String {
Thread.sleep(100L)
println("${Instant.now()}: After two")
return "World"
}
}
fun <T> Future(ex: ExecutorService, f: () -> T): Future<T> =
FutureTask(f).also { ex.submit(it) }
fun main() {
val repo = SuspendRepo()
println("${Instant.now()}: Start")
runBlocking {
val one = async { repo.findOne() }
val two = async { repo.findTwo() }
println("${Instant.now()}: Waiting")
println("${one.await()} ${two.await()}")
}
val pool = Executors.newVirtualThreadPerTaskExecutor()
val loomRepo = LoomRepo()
println("${Instant.now()}: Start")
val oneLoom = Future(pool) { loomRepo.findOne() }
val twoLoom = Future(pool) { loomRepo.findTwo() }
println("${Instant.now()}: Waiting")
println("${oneLoom.get()} ${twoLoom.get()}")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment