Davio
02/13/2023, 7:36 AMreformator
02/13/2023, 8:10 AMDavio
02/13/2023, 8:11 AMreformator
02/13/2023, 8:38 AMDavio
02/13/2023, 8:52 AMAdam S
02/13/2023, 9:02 AMDavio
02/13/2023, 10:46 AMDavio
02/13/2023, 2:03 PMWhen code running in a virtual thread calls a blocking I/O operation in theThis definitely sounds promising. So we still have the issue of parallelism, say I want to send 2 REST calls to other services at the same time and proceed when they're both done. From the same Loom JEP:API, the runtime performs a non-blocking OS call and automatically suspends the virtual thread until it can be resumed later.java.*
It is not a goal to offer a new data parallelism construct in either the Java language or the Java libraries.So I guess we might end up with a hybrid model where:
runBlocking {
val res1 = async { client1.getResponse() }
val res2 = async { client2.getResponse() }
res1.await() + res2.await()
}
is perfectly OK code.
The runBlocking isn't a problem if it's just blocking a virtual thread (as long as it does not pin itself to a certain carrier thread).reformator
02/13/2023, 2:09 PMDavio
02/13/2023, 2:16 PMfun main() {
val list = listOf(1, 2)
val result = list.parallelMap { it + 1 }
println(result)
}
fun <T, R> List<T>.parallelMap(transform: (T) -> R): List<R> {
StructuredTaskScope<Any>().use { scope ->
val futures = this.map { item ->
scope.fork { transform.invoke(item) }
}
scope.join()
return futures.map { it.get() }
}
}
We can use the aforementioned StructuredTaskScope, wrap it in Kotlin's version of the try-with-resources (which is 'use'). We then map the values into the list to a list of futures that we fork off with the scope.
We join the scope which waits for all of the futures to complete and finally just use the return values of the futures by calling get().
Now, get() has always been a blocking call and that's why Futures existed for a brief time in Java 7 before being 'superseded' by CompletableFutures.
Now that virtual threads are not blocking, it's funny to see they are reusing the old futures with their gets.Jarkko Miettinen
03/28/2023, 1:46 PMsuspend
or not), which Loom is not.streetsofboston
03/28/2023, 1:50 PMDispatcher
that would be backed by JVM's virtual threads.