Created
October 17, 2024 12:41
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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