5 ms·
The only difference between how virtual threads work and how async/await work is that you don't need to use await and don't need to declare async. Just call .ge
by spullara 4y ago
The only difference between how virtual threads work and how async/await work is that you don't need to use await and don't need to declare async. Just call .get() on a Future when you need a value - that is basically "await".
void doTwoThings() {
var f1 = doThingOne();
var f2 = doThingTwo();
var thingOne = f1.get();
var thingTwo = f2.get();
}
- mgraczyk 4y agoHow do you implement doThingOne? You should read the "structured concurrency" link in the article. You have to explicitly wrap the call to doThingOne in a future under a structured concurrency scope. The code example you wrote is not going to be possible in Java without implementing doThingOne in a complicated way.
- spullara 4y agoYou don't have to use structured concurrency. The two methods use a virtual thread executor and return the result of submitting work. Structured concurrency is great but not necessary. https://www.reactivesystems.eu/2022/06/17/introduction-to-project-loom.html https://www.reactivesystems.eu/2022/06/17/introduction-to-pr...
- merb 4y agogreat, now you have futures AND virtual threads. soo much better!
- gpderetta 4y agoIt is significantly better. The issue with futures is chaining them together and having to thread continuations by hand. Async/await is an improvement over that, but when you can just block instead they become much nicer to use.
- kagakuninja 4y agoJava Futures are lobotomized. What is really nice is to treat Futures as monads (as in Scala, and FP languages like Haskell). Then you can chain them together using calls to flatMap aka bind. Then you can use for-comprehensions (or the equivalent): for { a <- taskA b <- taskB c <- taskC } yield a + b + c There are a ton of other fancy tricks found in Haskell or libraries such as Cats.
- krackers 4y agoYou can have futures with "real threads" as well, futures are merely an abstraction to getting "output" of a thread in a non-blocking fashion.