202 points · by mxschumacher · 6y ago · 134 comments
This model of concurrency is so much better than the async/await model used by many other languages. No more colored functions [1], or worse Completable<Future>, promises et al. Nice stacktraces, debuggers that work plus no need for thread pools anymore. I can't wait for this to be ready for production.
Only drawback seems to be when calling native code. I guess it's the same problem that Golang has. Good thing is that the Java ecosystem is not that dependent on native stuff, so I think it's a fair tradeoff to make.
[1] https://journal.stuffwithstuff.com/2015/02/01/what-color-is-...
That's a property of the function, whether or not you want the type system to help you with it. I can call a function myRedFunction, but if it calls a blue function, it's blue.
> or worse Completable<Future> What is this? Future<Result> f = e.submit(() -> { ... return result; }); // spawns a new virtual thread
> This model of concurrency is so much better than the async/await mode
ThreadFactory tf = Thread.builder().virtual().factory();
ExecutorService e = Executors.newUnboundedExecutor(tf);
Future<Result> f = e.submit(() -> { ... return result; }); // spawns a new virtual thread
...
Result y = f.get(); // joins the virtual thread
I don't get it. This just looks like async/await (submit/get) with extra steps.
Why not just write Future<Result> f = async ( ... result; )
Result y = await (f);The problem is that in, say, C# or Kotlin, subroutines with the same semantics come in two different colours. The type system "helps" you distinguish between things that aren't meaningfully distinguishable.
> I don't get it. This just looks like async/await (submit/get) with extra steps.
You only need to submit if you want to do stuff in parallel and then join (also, there are no extra steps). The analogue to:
var a = await doA();
var b = await doB();
is just: var a = doA();
var b = doB();The distinction is important though, because it affects the observable behaviour of other effects present in these functions. https://glyph.twistedmatrix.com/2014/02/unyielding.html
The only cases where you want the same function to come in two colour variants is when it's a higher-order function, and in that case what you really want is not to ignore colour but for the function to be polymorphic over colour. (i.e. higher-kinded types).
Are these semantically the same?
Runnable action1 = () -> System.out.println("foo");
Runnable action2 = () -> System.out.println("bar");
action1.run();
action2.run();
var action3 = runAsync(() -> System.out.println("foo"));
var action4 = runAsync(() -> System.out.println("bar"));
action3.join();
action4.join();
> You only need to submit if you want to do stuff in parallel and then join (also, there are no extra steps).I'm not comparing parallel to sequential. My point was that we're already doing parallel programming:
CompletableFuture<Result> fx = CompletableFuture.supplyAsync(() -> result);
CompletableFuture<Result> fy = CompletableFuture.supplyAsync(() -> result);
Result x = fx.join();
Result y = fy.join();
Parent doesn't like the existing parallel model. New model looks like: // > plus no need for thread pools anymore.
ThreadFactory tf = Thread.builder().virtual().factory();
ExecutorService e = Executors.newUnboundedExecutor(tf);
// > No more [...] Completable<Future>, promises et al.
Future<Result> fx = e.submit(() -> { ... return result; });
Future<Result> fy = e.submit(() -> { ... return result; });
Result x = fx.get();
Result y = fy.get();
If going from the first to the second is an improvement, I don't understand the excitement. Especially when other languages look like: fx <- async (return 3)
fy <- async (return 3)
x <- wait fx
y <- wait fy(2) Can you give an example of an async and a non-async subroutine that have "the same semantics"?
Second, Java doesn't have async/await today. If Java was to introduce it, it wouldn't be compatible with the code written today. The big benefit of project loom is that code written today will get all the benefits of async/await without changing any code. In fact, because it's not important to pool threads, it actually gets easier.
The big problem with async/await in languages like C# or even coroutines in Kotlin is that it doesn't mix with the "old" api. The get the benefits you need to do a huge refactor of your code, and you need to make sure that any library you pull in is compatible.
Java's approach seems much better.
because altering the underlying thread pool can convert all existing code to fibers without syntax changes. This is the crux of "colored functions", two different signatures for async/non-async.
The implications for improving the performance of existing code are enormous. Most Java API's give you at least indirect control of the thread pool used. Which means they can be converted to fibers without updating the library.
In Java, executors are basically thread pools. If you can update the executor to use fibers the rest of the code is using fibers now. Your second example only converts a single call site to fibers. A thread pool could be used in hundreds of places.
In practice, this is a huge difference. I can update my Streams to use a fiber pool, and all across my app the hundreds/thousands of streams are using fibers now. Same story with REST and DB access. There's usually a single thread pool for each. A few lines of code to update the pools and my REST and DB calls are all using fibers.
Can you maybe recommend a good overview over all the current concurrent approaches and concepts, like async/await, and alternatives, and their advantages and problems? I would love to get a more recent overview on this.
I had the impression that most recent languages follow on the async/await concept. At least JS and Python. Maybe also Rust? Go? Erlang? And there are probably libraries for C++ to do the same, or maybe it is already integrated? I have to admit that I did not fully follow all this development.
The problem is that your split-up async function ceases to be a normal function. It doesn't use the stack in a similar way than normal functions. Furthermore, the executor / event loop is required for running those async functions.
So you can't call async functions from normal functions, because they aren't. You need to create an event loop and then hand the task over for it to process it. Your world splits up into sync and async functions.
Go and Erlang are going with the similar "lightweight thread" approach as Java's project Loom. On the other hand, JS, Python and C# have gone with async. I'm not sure if these languages actually need async, going with something similar as project Loom would have also fit, and would have been simpler from the user perspective, perhaps? But hindsight is 20/20.
Rust has also gone async, and I'd argue it's the only one of the pack who really have async/await as a necessity - this is because of two design requirements that differ from Java, C#, Python and JS: 1) must have native-level performance when calling foreign code that expects a C-like stack. Something like Loom doesn't provide that. 2) must not have an implicit default runtime.
Have you taken the CLR (a.k.a. .NET / C#) async await for a spin? Microsoft's done a great job of squaring away those details so the stack/thread discontinuity doesn't much matter.
For example, in Python you have this http client library called `requests`. It's very easy to use, but it is synchronous and you can't use it in when doing async/await. Instead you have to use a similar library called aiohttp. And it's like that for every single library or function doing any sort of IO, you need two versions of everything. Same thing happens in Node.js. You have `spawn` which is asynchronous and `spawnSync` which is synchronous. And so on.
And it doesn't stop with functions, this division goes across the language it self. For example in Python you have a `for` loop and an `async for` loop. Same in JS, you have `for` and `for await`. C# also has it's own `await forech` construct. It's like splitting the world for no reason.
The great advantage of Loom is that you don't need a parallel language, you can use the same http clients, database clients, filesystem libraries that you were using in a synchronous world, but now you will be able to use concurrently in millions of virtual threads.
As the article mentions, the whole reason why async/await was invented, is because doing concurrency with kernel threads is very expensive. They are slow to create and they use a lot of memory. Using Promises and an event loop you can run multiple concurrent operations in a single OS thread. This gives you the chance to achieve much more concurrency than running one operation per OS thread. The problem is that this changes the way you program a lot. Your code is not sequential anymore, your error handling is different, even some conditional operations are different. Async/await is just some syntactic sugar created to make this looks like the regular programming model. It makes the function calls look sequentials (by adding an `await` prefix), it makes the errors look like exceptions, it makes the for loops look like regular for loops. But this is just appearance. It's something that looks similar, but it's different, and that's why you can mix it with regular code.
Loom model is closer to Go and Erlang.
When project loom is implemented in Java, all code which makes use of threads today automatically gains all the benefits of the async/await model, without any refactoring.
Go and Erlang doesn't do the async/await thing. They only have one notion of concurrency (goroutines in Go, processes in Erlang). They don't require you to use async and await constructs, but they work similarly to async/await under the hood.
Coming from Java to JavaScript, I really, really yearn for the equivalent of ThreadLocals. For example, most Java logging libraries let you set a "context" object that can be used for logging a request ID or user ID anywhere down the call stack. You can't do that in Node, so instead you have to explicitly pass that context object down in all your function calls, or make use of brittle, complicated, hacky, not-fully-supported features like "continuation local storage".
Debugging stack traces in an async/await world is a mess because you don't get a nice "from the start of the request down to this call" view of the stack.
Perhaps most importantly, with Node at least you need to worry about starving your main event loop because there is only a single top-level main thread (but understand that's not inherent to the async/await issue in general).
While I understand why you feel that way today, you may find yourself some point in the future deeply, deeply detesting ThreadLocal. Sure it seems all convenient but all hell breaks loose when you need to use a threadpool, a future, an actor model...
Similarly, for the stacks, it's largely a tooling issue - if the debugger understands async, and the framework retains enough information about the origin of the promise, it can re-create the original stack trace, and combine it with the current one - .NET debuggers in VS and VSCode do this, as well, and WinRT even does this for C++.
As much as I want a more expressive language, all the explicit async/await, futures, callbacks, etc. junk needed just for your API handler to cooperate with concurrent requests (not even do its own parallel processing) keeps on sending me back to Go. I look forward to being able to write Java in the same style.
Others have given actual explanations, but I'll chime in with a bit of a tongue-in-cheek one: it's better than async/await because it doesn't have async/await (yet has all the benefits provided by them).
It could have been so much better.
As for C#, some kind of fibers appear to have been considered but deemed too hard or not worth the trade-offs. See here: https://github.com/dotnet/runtime/issues/11084
The acceptable alternative was, apparently, forcing to programmers to litter their code with words such as async/await/task in-between the words and symbols that actually describe the purpose of their program, should they want to take advantage of non-blocking IO. All the way throughout the call-stack, nonetheless. And you also get crap like this: https://github.com/dotnet/corefx/pull/4868
What I really like about this project is that we can keep Spring MVC applications in non-reactive form. Spring MVC came out with reactive framework for implementing APIs. But I'm not a fan of this style for a few reasons, plus there is millions of LOC doing it the non react implementation. By utilizing project Loom, we do not have to switch over to the Spring reactive way, and we can increase the performance of existing code.
EDIT: Here is the video: https://www.youtube.com/watch?v=Csc2JRs6470:
- he goes into Loom at 19:30.
- he goes into the demo at 24:00.
To explain: if you debug async code on Kotlin right now, you cannot single-step in a debugger, because the debugger attaches to a thread. But coroutines get scheduled on different threads all the time!
I wonder what this means for ThreadLocals and Locks? Will they work as before? If so, that is huge! Because locks don't work with async code either, for obvious reasons. The consequence is that the whole ecosystem is split in two parts! You cannot just use a Guava cache in Kotlin coroutine-based code.
If Loom manages to avoid all of this, this is fantastic news.
Yes. You can try that today: http://jdk.java.net/loom
Go was the first to solve colouring but they have it seems a less type safe solution
Is there something in particular about the JVM that makes it more difficult, or is it just that the work hasn't been done yet for some reason?
https://stackoverflow.com/questions/15410661/is-it-possible-...
Which it might continue to be. As Kotlin needs to support other backends than just the JVM.
I thought this was weird because IIRC Java 1.0 used green threads in Linux and it was a big deal when they moved to OS threads.
I’ve long believed that the IT world moves in cycles but this is a very clear example of exactly that. Java has gone from green threads to Posix threads and now back to green threads.
I do think it’s awesome (I love goroutines) and Threads in Java have become a but of a nightmare, made a little easier with executors and CompletableFutures. So this further improvement is great news.
But still... call me when the builder pattern is dead.
What Loom and Go do is to schedule green threads on a bunch of system threads and spawn more system threads when they get blocked doing synchronous system calls.
(And if you want to be pedantic, IIRC the green threads were originally mapped to the Java process, not a thread, because threads were either unavailable or immature in Linux when Java 1 came out; I can’t remember which)
The green threads on the JVM were not the same kind as green threads in Go (and Loom), they would block on IO. Can't speak for Loom, but Go automagically reschedules your green thread when it blocks which allows other threads to run while waiting.
The point is they weren't rescheduled when they would block in the JVM, every process has a main thread.
No it’s not the same thing - Java was previously M:1, then became M:M, and now Loom is M:N and also preserves M:M at the same time.
It’s a comment on the hype cycle. As a long time (since 1.0!) java developer, I like that Java has adopted a more efficient threading model. But they are certainly returning to a state where the JVM manages the threads rather than the OS, which certainly is the same as the original release, at least on Linux.
So it's more circumstance and necessity than hype.
A small caveat is that Erlang has a Refc binary type that is reference counted, when sending a message with a refc binary to another process on the same node the content isn't copied, just the reference value (like a pointer) and the reference count is incremented.
There is an area where copies could potentially be avoided, but I don't think they are. Recent versions of beam have an optional off-heap message queue feature; some software patterns have a proxy process that accepts messages and sends them as-is to another process; if the message is off-heap for the proxy process, and it would send to the next process off-heap, it could be possible to avoid copying it, but it might be a bit tricky. (I don't think this is done, but that's why I said AFAIK earlier)
https://news.ycombinator.com/item?id=17646169 from 2018
https://news.ycombinator.com/item?id=15599854 from 2017
https://news.ycombinator.com/item?id=23194215 - 3 comments from a few days ago
Moving this slow is why the implementation is much better than the same in C#, Kotlin, or JS.
I think I proposed this at a crazy idea talk at VEE a long ass time ago (10 years or more). It’s still a good idea but I guess not crazy anymore.
Does anyone have a reference to some up to date notes on the state of scalability of Linux and/or free-/dragonfly-bsd scalability at the process level?
I don't doubt processes are a bit heavy for scaling to a million active threads of execution - but it'd be nice to see what one could expect on a low end server (say 16 cores, 64gb ram) today?
Best reference I could easily find was this experiment that had 100k connections to mysql which has thread per connection model. Seems to handle it well
https://www.percona.com/blog/2019/02/25/mysql-challenge-100k...
There is an early access [1]
----
As for having in in JDK17, Ron provides an answer in the reddit thread [2]
[2] https://old.reddit.com/r/programming/comments/gkgzld/state_o...
I often wish the language had adopted it instead of the C#-like await async, since it’s just more straightforward.
I would consider myself a pretty harsh critic of Python but even I appreciate the elegance of the gevent approach to concurrency.
...and eating it too
Thread.startVirtualThread(() -> {});
Starts a new virtual thread that will run a synchronous method. Ok cool. C# already has: Task.Run(()=>{})
This will run synchronously on the shared thread pool. Tasks are futures and can return objects. Same as the Loom proposal.Optionally you can decide to opt into the await unboxing sugar by adding async to your method signature. There's arguably some double dipping with the async keyword on a method. It allows the await keyword to be used inside the method but also forces the caller into a different calling style. You can argue this shows API intent for cooperative threading. That said, you can still use async and sync interchangeably.
The syntax seems very similar to me.
Is there something else going on in Loom that I'm missing? Is it a matter of how the virtual threads are scheduled/preempted vs how other languages with async/await schedule their tasks?
Loom with "Thread.startVirtualThread" will run something on a userland / green thread (ie. not a kernel thread so no context switching and blocking it "costs" practically nothing). async-await is actually a subset of wat Loom does in the sense that Loom allows for far more then just async-await. Most of the "hate" for async-await is probably because it leads to the "what color is your function" [1] problem.
[1] https://journal.stuffwithstuff.com/2015/02/01/what-color-is-...