264 points · by ludovicianul · 4y ago · 133 comments
Should be interesting to see what shakes out of all this. When you need structured concurrency, imo async and coroutines are nicer than what fork/join and what Java has so far.
Here's the example from the JEP:
Response handle() throws ExecutionException, InterruptedException {
try (var scope = new StructuredTaskScope.ShutdownOnFailure()) {
Future<String> user = scope.fork(() -> findUser());
Future<Integer> order = scope.fork(() -> fetchOrder());
scope.join(); // Join both forks
scope.throwIfFailed(); // ... and propagate errors
// Here, both forks have succeeded, so compose their results
return new Response(user.resultNow(), order.resultNow());
}
}I don't see the advantage to this over async/await style programming. I think you'll see very similar error cases with unobserved exceptions and such.
The advantage is that the method signature is indistinguishable from a blocking method. The subtle difference is that scopes close within a method where as async tasks can continue. I suppose you could see an even worse coloring where scopes and futures are used in half the methods instead of async.
I'm trying to wrap my head around how this would play out if you were attempting to write a GUI or something where the pattern is a single main thread. I suppose it would work just fine and look very similar to async style programming but with a lot more code one tab to the right.
Which is true around the M:N stuff, but the missing piece is the communication. Go has channels, Erlang uses the actor model, do you know if there are any plans to have something like this in Java?
Frequently I've written applications that use Executors, Reactive Streams, etc. and found that frameworks like that rarely, if ever, provide a good answer for how to tear a processing system down at the end. It's completely practical to use a stream processing framework to process batch jobs, but to get correct answers you have to shut the thing down at the end. I've frequently built teardown systems and it's always left me with the feeling that system programmers should occasionally climb down from their high horse and write an application.
From a Kotlin co-routine point of view Loom is about the JVM gaining some low level optimization features that will slightly enhance co-routine performance on newer JDKs (not that this was actually much of a problem) but will otherwise not really add anything new in terms of features as co-routines already had pretty much all of the features.
Of course it's nice for Java to gain a few new APIs for this. But it's not like there was a shortage of asynchronous programming APIs. If you intend to use this as a drop in replacement for Threads, read up on blocking vs. non blocking IO or you'll be finding out the hard way why Java uses a lot of real threads when dealing with blocking IO. If on the other hand you were already using non blocking IO, using Threads would not have been a thing you'd be doing. Hint, virtual threads in the same thread will all block if you use blocking IO.
With Kotlin, co-routines, the compiler will issue warnings if you call into blocking Java stuff from a co-routine and nudge you to deal with that by of-loading to a threaded co-routine context.
This is apparently not the case in the new JDK implementation of virtual threads. According to JEP 425 (linked in the OP):
> Application code in the thread-per-request style can run in a virtual thread for the entire duration of a request, but the virtual thread consumes an OS thread only while it performs calculations on the CPU. The result is the same scalability as the asynchronous style, except it is achieved transparently: When code running in a virtual thread calls a blocking I/O operation in the java.* API, the runtime performs a non-blocking OS call and automatically suspends the virtual thread until it can be resumed later. To Java developers, virtual threads are simply threads that are cheap to create and almost infinitely plentiful. Hardware utilization is close to optimal, allowing a high level of concurrency and, as a result, high throughput, while the application remains harmonious with the multithreaded design of the Java Platform and its tooling.
So new Java virtual threads really are meaningfully different from Kotlin coroutines.
What Loom likely does for blocking IO is implement some continuation wrappers around that do the right thing; which is indeed nice.
With Kotlin co-routines, you'd mostly avoid using blocking IO in favor of using non blocking IO. With the exception of legacy code that uses blocking IO which up until now you'd simply park on a threaded co-routine context for that reason. So, yes this is a very nice feature that I wasn't aware of and thanks for pointing that out. It won't massively change my life because there's not a whole lot of blocking IO happening in most things that I use. But it's great for transitioning legacy code to more modern frameworks without a lot of invasive changes.
The otherwise problem is that you end up with two worlds, the non-async ad the async ones, and they can't really call each other without a lot of problems.
The new JVM features will allow you to write async code while still being able to call any functions, that'll make it actually useful.
Kotlin's co-routines are simply syntactic sugar for simple callbacks but without the boiler plate. If it has some kind of success / fail callback mechanism, you can create a co-routine from it. Futures, Promises, a Flux, whatever. That's all that happens and the co-routine library comes with extension functions for all these.
I'm not sure what you measured relative to what. But I bet it is some blocking/expensive code actually taking a while before it suspends or something similarly sub-optimal. Of course the key bottleneck with virtual threads would be the scheduler loop that runs all these co-routines. The main contribution of Loom is moving that stuff into the JDK and possibly optimizing the hell out of that. But other than that it does something very similar to what other green/light weight threads have to do necessarily.
Basically any time any virtual thread does something expensive/blocking, all the other virtual threads suffer. If you see a browser app freeze for a bit, that's usually what happened. Loom adds a thing called continuations which literally have a suspend method that tell Loom that it is now safe to switch to another Fiber. Failure to use suspend correctly, will result in the same stuttering behavior on Loom: things will freeze or block until whatever is running calls suspend: only 1 virtual thread executes at the same time. That's the whole point. For non blocking IO this is fine. If you are doing computationally intensive stuff, you either need to suspend frequently or use some thread pool. Otherwise the virtual thread will hog the CPU whenever it runs.
As for the two worlds, I can call any function from a suspend function. Just not the other way around without creating a co-routine context. What Loom adds is basically a better light weight thread scheduler. Under the hood it likely does many of the same things that Kotlin already did.
https://paulhoule.github.io/pidove/apidocs/com/ontology2/pid...
that involve a slightly awkward state machine (and some complexity around initialization and teardown) that can be avoided with coroutines such as Python's generators.
* clean call stacks - stack traces returned by current async libraries are very difficult to understand
* no need to colour functions, no need to worry if your function is suspendable or not and in which context you are using it
Java record pattern matching in JDK 19 - https://news.ycombinator.com/item?id=31378896 - May 2022 (155 comments)
Using Java's Project Loom to build more reliable distributed systems - https://news.ycombinator.com/item?id=31314006 - May 2022 (91 comments)
JEP proposed to target JDK 19: 425: Virtual Threads (Preview) - https://news.ycombinator.com/item?id=31236855 - May 2022 (212 comments)
Achieving 5M persistent connections with Project Loom virtual threads - https://news.ycombinator.com/item?id=31214253 - April 2022 (145 comments)
Loom: Project Loom Early-Access Builds - https://news.ycombinator.com/item?id=28191308 - Aug 2021 (76 comments)
Project Loom and Structured Concurrency - https://news.ycombinator.com/item?id=25300233 - Dec 2020 (108 comments)
Project Loom: Fibers and Continuations for the Java Virtual Machine - https://news.ycombinator.com/item?id=15599854 - Nov 2017 (41 comments)
However, given the number of excellent JVM languages, especially Kotlin, I'm curious what the general consensus is for starting new projects. That is, if I were starting a greenfield project, I think I would definitely use Kotlin over Java - Kotlin doesn't have to deal with the backwards compatibility concerns of Java, and thus does away with some of the problematic annoying complexity of Java. E.g. first class language support for nullable/optional types I think is critical these days - Java has bolted on an Optional wrapper, but it's cumbersome and doesn't provide the kind of strong guarantees that a language-implemented version does.
So what does the HN community think? Would you use another JVM language over Java if you were starting a new project?
Java is coming along quite nicely. Its pattern matching looks to be better implemented than Kotlin's (e.g. destructuring implementation). Same with string interpolation (https://openjdk.org/jeps/8273943). And now with Loom, no need to maintain two separate API surfaces for sync vs async. It has the last mover advantage.
Some years ago, my division at <large company> decreed Scala was the way of the future. All new development was to be done in Scala. We were offered training classes. We formed book clubs. We paired, shared, and opined as we tried really hard to do functional programming correctly. We genuinely tried, and then we gave up. The specific reasons would better suit another post, but it was a grassroots developer-led effort that led us to abandoning Scala.
At this point, we have backend code in NodeJS, Scala, GoLang (this is currently a performance-sensitive one-off), and Java. That's a problem for code reuse, tooling reuse, and general maintenance. If we were to write new components in Kotlin, we would be making the problem worse. At this point in time Java is our safe fallback.
In the future we may try a different language again, but for now there needs to be a really good reason to add to our tech stack. I suspect most new projects will continue to be Java for quite some time, because we're not going to rewrite all the Scala and NodeJS code "just because". It will slowly get replaced as it stops working, or as we find reasons to replace it other than "it's in a language we don't like". Until then, our polyglot set of codebases is too intimidating and devs are going to resist adding another language to it.
I don't agree with this. Kotlin is essentially a drop-in replacement for Java, so much so that you can replace your Java classes _one by one_ with Kotlin classes. The build tools, frameworks etc are mostly the same, so no real changes required in the environment. (All this is not true for Scala, for example.)
From one perspective, one might argue that Kotlin didn't do enough (eg. it has ADTs but no pattern matching), on the other hand, this is exactly why it is so easy to step up. You can also very quickly get productive in it coming from Java, there is no need to use advanced stuff like async/await, and there are very few caveats you need to worry about.
Just my 2c, based on experience.
https://typelevel.org/cats-effect/
The language, the community and customs are great. You don't have to worry about nulls, things are immutable by default, domain modelling with ADTs and patter matching is pure joy.
The tooling available is from good to great and Scala is big enough that there are good libraries for typical if not vast majority of stuff and Java libs as a reliable fallback.
It's not some panacea though, and at the end of the day Java is the system language of the JVM. New VM features are not built to cater to the guest languages. In the case of virtual threads we have a directly competing "async" solution to Kotlin coroutines. So you may see further ecosystem split between libraries catering to Android and those catering to backend work.
no. I'm never a fan of anything like typescript or Kotlin where it's transpiled (yes i know Kotlin is compiled down to JVM byte code) end up dealing with more headaches and troubleshooting in the end.
First, yes, I agree that setting it up initially and understanding all the various tsconfig options can be a pain. But it's also largely a one-time cost, and honestly over the past couple years I really didn't have any "weird troubleshooting" problems once I got it working. Also, these days more is being done to make TypeScript easier to run out of the box, e.g. Deno.
But the benefits of using TypeScript are vast, even from an individual programmer perspective, nevermind the huge benefits of using it to allow for refactoring and better comprehension in a larger team. The autocomplete benefits alone that I get with it in VSCode are worth it.
[1] https://openjdk.org/jeps/405
See how sucessfull Kotlin/JS and Kotlin/Native are on the wild.
The same libraries that can be used from Kotlin?
The toolchain in both cases is basically IntelliJ (rebranded as Adroid Studio)
At that point one could also say "why Anrdoid?".
Kotlin was designed to replace Java 1.6 and that's about all it's good for.
Not sure what K was designed for. But we use it to fix J's billion dollar "implicit nulls" mistake, and terse syntax (making it useful for templating: Kotlinx.html), and pass-as-value method references. We love it's hang towards immutability.
K is not Haskell, but it sure feels a lot safer that J (where a lot of strings were used to refer to methods, and strings+Groovy was used to do templates).
Bottom line: I'm too old --and life's too short-- for NPEs.
We went from having RAD IDE's that produced native UIs to everything has to be done in electron because nobody is innovating in the Desktop GUI space.
Very much nicer this way, and although a few businesses are still stuck on 6 or 8 most places seem to be aiming to stay current with Long Term Support (LTS) releases (of which 17 is the current LTS and 21 will be the next one).
Some of the innovations were value types extensions, AOT compilation or JIT caches, and until OpenJ9 came to be, that usually was only available to commercial clients.
I mean, I'd like to see better typing because the current generics are too basic, and you always end with casts and `isAssignableFrom`. Is there anyone working on types for Java, like in TypeScript and Rust?
Another huge issue for me is null-type safety. The latter is basically the only reason we use Kotlin right now. We would be happy to migrate to the latest Java if it fixes the nulls. I'm wondering what prevents adding a simple syntax sugar like optional !-suffix for non-nullable definitions. Like `void fooBar(String! path)`, which should prevent at the compiler level from passing a null argument. Could that work?