News for hackers. Stuff that matters.
Re:Project Loom and Structured Concurrency by jnwatson on Friday December 04, 2020 @08:51AM (#25302181)
I have a lot of experience using concurrency in Go, and for the last couple years have been at the bleeding edge of Python async. The tradeoffs between the two approaches are immense.

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.

Re:Project Loom and Structured Concurrency by pron on Friday December 04, 2020 @09:10AM (#25302350)
* Java offers both user-mode and kernel threads. You pick at creation, and can even plug your own scheduler.

* 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.

Re:Project Loom and Structured Concurrency by jayd16 on Friday December 04, 2020 @11:50AM (#25304538)
One headache I see that no one seems to mention is thread affinity seems a lot harder to manage in an implicit system. Many patterns use a single thread for synchronization but often times one thread is special. UI systems often have a UI thread that controls the GLContext or what have you. In something like C#'s async, you can easily schedule tasks off and on that thread. I'm not sure how you could do this implicitly. Loom seems to keep around native Threads for this sort of thing?

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.

Re:Project Loom and Structured Concurrency by pron on Friday December 04, 2020 @12:12PM (#25304906)
> I'm not sure how you could do this implicitly.

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.

Re:Project Loom and Structured Concurrency by vbezhenar on Saturday December 05, 2020 @12:23PM (#25316281)
>>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.

Is it? I recently had to write some simple code with C to interact with WinAPI and JNI was pretty straightforward to do.

Re:Project Loom and Structured Concurrency by ryanworl on Friday December 04, 2020 @09:24AM (#25302467)
Is it possible to override the scheduler from user code? i.e. if you wanted to control scheduling yourself for some reason.
Re:Project Loom and Structured Concurrency by pron on Friday December 04, 2020 @09:30AM (#25302545)
Yes, and even on a per-thread basis.
Re:Project Loom and Structured Concurrency by ryanworl on Friday December 04, 2020 @09:38AM (#25302648)
Thanks! Is there an example "Hello World" executor that demonstrates the minimum functionality needed?

I would like an executor that runs all tasks on a single thread and schedules them deterministically for testing.

Re:Project Loom and Structured Concurrency by pron on Friday December 04, 2020 @09:49AM (#25302787)

    var myThreadFactory = Thread.builder().virtual(Executors.newSingleThreadExecutor()).factory();
All threads created by this thread factory will be scheduled to the same kernel thread.
Re:Project Loom and Structured Concurrency by Cojen on Friday December 04, 2020 @11:02AM (#25303792)
Does this example fully answer the question? Does this allow the tasks to be scheduled deterministically? If I'm very careful and write the tasks such that they make blocking calls at specific locations, then yes. Otherwise, is there any feedback to inform me that tasks are switching context at places I didn't expect? Is it possible to define a custom scheduler that can simply print debug messages at every context switch?
Re:Project Loom and Structured Concurrency by pron on Friday December 04, 2020 @11:13AM (#25303960)
It answers the question with a "hello, world." To do more sophisticated stuff, like what you want, you'll need to replace or wrap the standard single-thread Executor with your own Executor. There is exactly one method you need to implement. For example:

    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();
Re:Project Loom and Structured Concurrency by jerf on Friday December 04, 2020 @09:23AM (#25302464)
I don't think "task cancellation" is quite the major difference you think. If you model it as thread A wants to cancel thread B, then while threading means that A runs and cancels B, but B may need some time to catch up, the async world has the problem of thread A running at all to cancel B, if B is having a problem that requires cancellation. It's "obvious" and "safe" until it doesn't happen at all.

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!)

Re:Project Loom and Structured Concurrency by jnwatson on Friday December 04, 2020 @09:39AM (#25302654)
Async, and cooperative multitasking in general, requires all members participate in the contract: you shall not block and you shall not go too long until yielding. Once a piece of code violates that, all bets are off. Python has explicit debugging mechanisms to help a developer detect the latter.

Cancel safety is less about killing an out-of-control task, and more about making sure the state after cancelling a task is consistent.

Re:Project Loom and Structured Concurrency by didibus on Saturday December 05, 2020 @06:42PM (#25319512)
> you shall not block and you shall not go too long until yielding

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".

Re:Project Loom and Structured Concurrency by jayd16 on Friday December 04, 2020 @12:20PM (#25305015)
>you shall not block and you shall not go too long until yielding

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?

Re:Project Loom and Structured Concurrency by dnautics on Friday December 04, 2020 @10:49AM (#25303618)
> but if you want to see a runtime that really has the asynchronous exceptions thing figured out, go look at Erlang.

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)

Re:Project Loom and Structured Concurrency by earthboundkid on Friday December 04, 2020 @11:18AM (#25304017)
Cancellation is a little tricky. If things can cancel at any point, then it's impossible to write safe/correct code. Async has the advantage that the await calls are natural sync points, so it's (probably) safe to cancel there. But historical experience has also shown that people will forget to yield when they should, and it will lead to cooperation problems.

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...

Re:Project Loom and Structured Concurrency by jayd16 on Friday December 04, 2020 @12:15PM (#25304943)
If Loom isn't adding cancellation tokens to the core library then its going to be a major difference. That said, the Java way was already for runnables to cancel themselves with some kind of volatile cancel bool so I expect that's all we'll get.

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.

Re:Project Loom and Structured Concurrency by throwaway894345 on Friday December 04, 2020 @11:09AM (#25303894)
I've had similar experiences, but I don't much care for async Python. In particular, it's way too easy to block the event loop either by accidentally calling some function that, perhaps transitively, does blocking I/O (this could be remedied if there was no sync IO) or simply by calling a function which is unexpectedly CPU-bound. And when this happens, other requests start failing unrelated to the request that is causing the problem, so you go on this wild goose chase to debug. Sync I/O is also a much nicer, more ergonomic interface than async IMO. And then there are the type error problems--it's way too easy to forget to `await` something. Mypy could help with this, but it's still very, very immature. Lastly, last I checked the debugger couldn't cope with async syntax--this is obviously not criticizing the async approach in general, but I wanted to round out my complaining about async Python.

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.

Re:Project Loom and Structured Concurrency by breatheoften on Friday December 04, 2020 @02:36PM (#25306664)
I'm not sure I really think of function coloring as a "problem" ...

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 ...

Re:Project Loom and Structured Concurrency by jdlshore on Friday December 04, 2020 @04:23PM (#25308223)
There was a series of essays about esoteric language features posted here a few weeks ago, and one of them was exactly what you're talking about. It was a functional language, with the ability to mark functions as involving I/O, non-terminating, or (I think) arbitrary custom "colors."

It was an academic language, but very interesting. Sadly, I don't remember the name. Maybe somebody else can post the link.

Re:Project Loom and Structured Concurrency by nsm on Saturday December 05, 2020 @01:58PM (#25317235)
Re:Project Loom and Structured Concurrency by didibus on Saturday December 05, 2020 @07:32PM (#25319802)
Wow neat. This has to be one of the most promising new language I've seen in a while.
Re:Project Loom and Structured Concurrency by jdlshore on Saturday December 05, 2020 @03:02PM (#25317782)
That’s the one! Thanks.
Re:Project Loom and Structured Concurrency by svieira on Friday December 04, 2020 @11:54AM (#25304623)
A couple of excellent articles on the different ways of thinking about the choice (of when to yield) vs. color (virality of choice) problem:

* Choice is bad: https://journal.stuffwithstuff.com/2015/02/01/what-color-is-... * Choice is good: https://glyph.twistedmatrix.com/2014/02/unyielding.html