* Loom's virtual threads are completely scheduled in library code, written in Java.
* FFI that bypasses the JDK and interacts with native code that does either IO or OS-thread synchronization is extremely rare in Java.
* Cancellation is the same for both.
Also, IMO, coordination is simpler for threads than for async. Where they differ is in their choice of defaults: thread allow scheduling points anywhere except where explicitly excluded; async/await allows scheduling points nowhere except where explicitly allowed. Putting aside that some languages have both, resulting in few if any guarantees, threads' defaults are better for correct concurrency. The reason is that correctness relies on atomicity, or lack of scheduling points in critical sections. When you explicitly exclude them, none of your callees can break your correctness. When you explicitly allow them, any callee can become async and break its caller's logic. True, the type system will show you where the relevant callsites are, but it will not show you whether there is a reliance on atomicity or not.
Async/await does, however, make sense for JavaScript, where all existing code already has an implicit assumption of atomicity, so breaking it would have broken the world. For languages that have both, async/await mostly adds a lot of complexity, although sometimes it is needed for implementation reasons.
I would be really interested in seeing a UI system written with Loom.
>FFI that bypasses the JDK and interacts with native code that does either IO or OS-thread synchronization is extremely rare in Java.
I would also argue its rare because its hard to do. This is a self fulfilling argument. In C#, a very similar language, its much more common to do that sort of thing because its easier. C# is chosen for games and other apps because it can interop with native more easily.
See https://news.ycombinator.com/item?id=25301246
> I would also argue its rare because its hard to do.
I would argue it's mostly because the Java ecosystem is so rich (often richer than "native" alternatives), there's hardly ever a need to do it. BTW, as of JDK 16, you'd be able to do FFI in pure Java: https://openjdk.java.net/jeps/389 It's not yet entirely convenient -- that would come later.
>I would also argue its rare because its hard to do.
Is it? I recently had to write some simple code with C to interact with WinAPI and JNI was pretty straightforward to do.
I would like an executor that runs all tasks on a single thread and schedules them deterministically for testing.
var myThreadFactory = Thread.builder().virtual(Executors.newSingleThreadExecutor()).factory();
All threads created by this thread factory will be scheduled to the same kernel thread. Executor ste = Executors.newSingleThreadExecutor();
Executor myExecutor = task -> {
if (task instanceof Thread.VirtualThreadTask vtt) System.out.println("Scheduling " + vtt.thread() + " on " + Thread.currentThread());
ste.execute(task);
if (task instanceof Thread.VirtualThreadTask vtt) System.out.println("Descheduled " + vtt.thread() + " from " + Thread.currentThread());
}
var myThreadFactory = Thread.builder().virtual(myExecutor).factory();This is a pervasive problem with the async/await model. As it scales up the probability of something failing to yield when it should and blocking everything else continually goes up as the code size increases, and then the whole model, correctness, practicality, and all, just goes out the window. While it is small for small programs, and it the scaling factor often isn't that large, it is still a thing that happens. Entire OSes used to work that way, with the OS and user processes cooperatively yielding, and what killed that model is this problem.
Also, I'm writing a lot of code lately where I can peg multiple cores at a time, with a relatively (if not maximally efficient) language like Go; having to also write it as a whole bunch of OS processes separately running because my runtime can only run on one core at a time is a non-starter, and "async/await" basically turns into a threading system if you try to run it on multiple cores in one system anyhow.
These two fatal-for-me flaws mean it's a non-starter for a lot of the work I'm doing anyhow, regardless of any other putative advantages.
(As I mentioned, I'm using Go, but if you want to see a runtime that really has the asynchronous exceptions thing figured out, go look at Erlang. Having a thread run off into never-never-land and eating a full CPU isn't fun, but being able to log in to your running system, figure out which it is using a REPL, kill just that thread, and reload its code before restarting it to fix the problem, all without taking down the rest of your system is not an experience most of you have had. But it can be done!)
Cancel safety is less about killing an out-of-control task, and more about making sure the state after cancelling a task is consistent.
Arn't those effectively the same?
I think the only contract is "you shall not go too long until yielding". Or if you're designing for performance, not for responsiveness, it might be: "you shall not hold unto CPU and IO resources that you're not using".
Eh... you as the caller have control on how a task is run. If you want it on a different thread and non-blocking, or simply deferred, you can. You have a lot of control.
With an implicit system you have much less control. Loom seems to solve this by letting you explicitly schedule tasks anyhow?
The erlang VM does indeed have async exceptions, and resource management figured out. Usually you can just kill an erlang process and you don't have to clean up after it's open sockets, file descriptors, etc.
It's also possible to hook the C FFI system to take full advantage of that: https://youtu.be/l848TOmI6LI
(Disclaimer: self promotion)
I think the best approach has to look something like Go's, but perhaps a bit more structured (dynamic scoping[1] might help perhaps with task nurseries[2]). Unless you're writing extremely low level code, you want your language runtime to intercept all syscalls and figure out the async story for you. The language should handle making sure that the M:N mapping works out, no one opens a socket the wrong way etc. Then for you as the program writer, your responsibility is just setting explicit cancellation points as part of the general error handling approach. It's still not perfect, but I think that would be the next evolution from what exists today.
[1] https://blog.merovius.de/2017/08/14/why-context-value-matter...
[2] https://vorpus.org/blog/notes-on-structured-concurrency-or-g...
From the article: >Clearly the intent is also to cancel the child thread. And this is exactly what happens.
I find this to be a bold choice. In C# you can detach children and such. Should be interesting to see if this gets added later.
I don't mind working with goroutines personally--I use them sparingly, only when I really need concurrency or parallelism. This takes some discipline (e.g., not to go crazy with goroutines and/or channels) and a bit of experience (in the presence of multiple goroutines, what needs to be locked, when to use channels, etc), so if you're relatively new and very impatient or undisciplined you probably won't have a good time (which isn't to say that if you dislike goroutines you must be a novice or undisciplined!). But for me it's nearly an ideal experience.
facebook is experimenting with auto differentiation for Kotlin and looks like it's adding a new "differentiable" function color -- https://ai.facebook.com/blog/paving-the-way-for-software-20-...
It looks very easy to reason about and use to me ... and i personally find async a similarly useful marker ... It's about being able to push constraints from caller arbitrarily far down the callee stack -- which is really not something that types support at all but provides for a very high confidence variety of constraint -- and high confidence constraints seem to me like they convey a ton of information.
I've been wondering actually whether "function colors" might actually just be a good way to create a whole variety of strong statically enforceable constraints for functions. It seems like they lead to very good and simple programmer mental models ...
Are there languages that offer "user definable" function colors? I can think of a lot of application domains that would be much better served by these kinds of constraints than oo or other type-centric approaches ... it would be ridiculously useful to be able to mark a function with the "MyDomainBusinessLogic" color and get assurances that such a method can only call other functions annotated with that color ... would provide an easy way to iterate on app specific abstractions provide compiler assistance for the communication of layering intent -- rather than a bunch of poorly specified words in documents that try to communicate layering intent to other developers -- in language that is either sufficiently precise as to be incomprehensible -- or sufficiently vague as to be subject to (mis)interpretation ...
It was an academic language, but very interesting. Sadly, I don't remember the name. Maybe somebody else can post the link.
* Choice is bad: https://journal.stuffwithstuff.com/2015/02/01/what-color-is-... * Choice is good: https://glyph.twistedmatrix.com/2014/02/unyielding.html
With the virtual thread model you have:
* No function coloring problem. This also means existing code is easier to port.
* possibility of transparent M:N scheduling.
* Impedence mismatch with OS primitives.
* Much more sophisticated runtime.
* Problematic task cancellation.
* Lots of care still needed for non-trivial inter-task synchronization.
With the async API model you have:
* Viral asyncification (the method color problem).
* Simpler runtime.
* Obvious and safe task cancellation.
* Completely orthogonal to parallelism (actually doing more than one thing simultaneously) for good and for bad.
* Inter-task coordination is straightforward and low-overhead even for sophisticated use cases.
* Higher initial learning curve.
I'm leaning toward liking the async approach more, but that might be just because I'm deep in the middle of it. I think the biggest argument in favor of virtual threads is the automatic parallelism; that's also the biggest argument against: free running threads require more expensive synchronization and introduce nondeterminism.