151 points · by emccue · 4y ago · 114 comments
That's not true at all. The megabyte(s) of stack space is virtual, spawning a thread only requires a few kilobytes of memory initially, and is a lot cheaper than many realize.
All I do know is that in Java I cannot create this many threads and in the talks given about Project Loom this is given as the explanation as to why.
https://www.youtube.com/watch?v=EO9oMiL1fFo @ ~4:00
Is it maybe not the actual spawning but some "switch" that flips once you start using the thread?
I'll update the post or leave a comment with a correction once I understand exactly what you mean
> OpenJDK implements threads as thin wrappers around the OS thread [...] OS threads are expensive, by which I mean that we cannot have too many of them. Maybe a few thousand active ones, maybe ten thousand active ones, but that's about it. And the reason for that is that the OS doesn't know the various languages, and the most costly component of a thread is its stack, and the operating system doesn't know how the various languages it might support makes use of the stack. So it must address the worst case and allocate a very large stack. It's usually on a megabyte scale. And even though we use virtual memory and not all of it is committed to physical memory, once we touch a page it becomes committed – it can't be uncommitted again because the OS doesn't know how the stack is used. And in any event, all the operations are done at a page granularity which is 4k, it's also not that small.
There may also be arbitrary OS-specific limits. For example on Linux there is system-wide limit on the number of threads, controlled by /proc/sys/kernel/threads-max (docs: https://www.kernel.org/doc/html/latest/admin-guide/sysctl/ke..., see also: https://stackoverflow.com/a/8849114). On my system it's ~60,000 (with 8G RAM).
I wonder if this could be solved by the code itself. Every so often tell the OS that you don't need all of the stack pages that are currently unused.
Of course getting the "every so often" right to avoid a huge slowdown in edge cases isn't easy.
Based on what the top person said, I'm thinking that they don't get a large stacks until they cross some threshold of use, but I want to make sure.
I've seen people OOM themselves by setting the default thread stack size massively high - they had likely gotten confused with the args (they'd used -Xss when I think they meant -Xms) and given their threads 1GiB of stack each.
I can't speak to how Java manages stack size between itself and the OS though, I'm sure there's deep magic there.
[1] https://docs.microsoft.com/en-us/windows/win32/api/processth...
(I'm not agreeing or disagreeing; I'm only trying to helpfully clarify)
You shouldn't normally call `Thread.currentThread().interrupt()` inside a `catch (InterruptedException e)` unless, perhaps, you don't throw anything. That would prevent any blocking operation inside cleanup code from working. As a general rule, a thread's interrupt status is set or InterruptedException (or some other exception) is thrown, but not both. That is how JDK methods also do it. If they throw — they clear the interrupt status.
I only started doing this recently after this advice here
https://discord.com/channels/544924237773668373/930457954346...
I'll clear it from the examples
There's also some optimizations that could be made. Instead of having
synchronized (seen) {
if (!seen.contains(u)) {
seen.add(u);
// ...
}
}
you can get rid of the synchronization with // seen = ConcurrentHashMap.newKeySet()
if (seen.add(u)) {
// ...
}You lose type safety when using it. I'm guessing with generics in 1.18 now, we'll see an updated generic version of sync.Map whenever a bunch of new collection types are added to the standard library that take advantage of generics.
Like maybe a set. That isn't a map[T]interface{} and can do things like unions and intersections so I don't have to implement it with for loops.
In one of my first Go programs, I used mutexes to avoid concurrent writes in a critical part. Then I moved the writing process into a goroutine that receives its input through a channel of size 1. In my case, the later code was easier to maintain and more performant than the former, mutex-based, code.
You can do so in one of two ways using the context API (https://go.dev/blog/context) while keeping the code synchronous and idiomatic:
package main
import (
"context"
"fmt"
"time"
)
func say(ctx context.Context, s string) {
for i := 0; i < 5; i++ {
select {
case <-time.After(100 * time.Millisecond):
fmt.Println(s)
case <-ctx.Done():
return // Operation canceled or timed out.
}
}
}
func main() {
ctx := context.Background() // Use context cancellation semantics.
go say(ctx, "world")
say(ctx, "hello")
}
If the code is reasonably performance sensitive AND there's a high degree of likelihood the context is canceled before the operation completes, you can use a time.Timer similar to what follows: for i := 0; i < 5; i++ {
func(i int) { // Wrap in closure expressly to support defer statement.
t := time.NewTimer(100 * time.Millisecond)
defer t.Stop()
select {
case <-t.C:
fmt.Println(s)
case <-ctx.Done():
return // Operation canceled or timed out.
}
}(i)
}They also make use of constructs that are overkill for such simple examples. For example, the first example could be written as:
Thread.startVirtualThread(() -> say("world"));
say("hello");
which would also replicate same concurrency bug as in the original Go program (the Java example, as written, does not have that bug, but neither would var t = Thread.startVirtualThread(() -> say("world"));
say("hello");
t.join();
).Go makes certain concurrency bugs easy to introduce and hard to find, while Java helps avoid them, but that is also not easy to see from these particular examples.
Disenchanted to hear (some) concurrency bugs easy to introduce and hard to find in Go. Could someone mention how does this compare to Elixir?
These cases work flawlessly in Go, in my experience:
* Batch 10 tasks and run them concurrently (using WaitGroups).
* Locking resources while reading and writing with a mutex like sync.RWMutex, using .Lock() and .Unlock(), often together with defer.
* Locking resources while only reading with a sync.RWMutex, using .RLock() and .RUnlock(), often together with defer.
* Running code "in the background" with goroutines, ie. go func() { <code goes here> }().
* Detecting race conditions by building with go build -race and then running the program.
However, when using channels, select, closing channels, waiting on channels in a for loop etc, things can easily become more subtle.
On a general basis, I disagree that concurrency bugs are easy to introduce and hard to find in Go. However, pure functional programming languages like Haskell, with little state, will always have the upper hand when it comes to concurrency.
See also:
https://gobyexample.com/waitgroups
https://gobyexample.com/mutexes
I would have used .startVirtualThread more if I wasn't under the impression that I needed to do Thread.currentThread().interrupt() when catching and re-throwing as a RuntimeException.
So I was choosing between the noise of that in the examples and the noise of the executor + submit with a lambda that returned null.
For me Golang has far weaker and less flexible error handling semantics.
And concurrency is more verbose in Java but it's easy enough to abstract it behind a wrapper.
Where as you can't escape Golang's error handling.
I do believe you probably have more control over Java's threads, making them a bit more verbose. But, both Java itself - as you mention - and languages built on top of the JVM have ways to make it less verbose.
While in Java, it tries to mostly keep the existing Java syntax.
I guess people that write Java are used to a lot of "lasagna" all-is-object boilerplate and ignore it. The same way go people are used to ignore the `err != nil` lines everywhere.
I do however wonder, now, what I’m missing out on with other languages, particularly swift and rust.
In Kotlin coroutines you can .cancel() a coroutine, but Go doesn't allow to cancel goroutines.
Nearly all SQL Database access goes through it and it won't be rewritten in any practical time scale. It can't be meaningfully async without a rewrite and kotlin's coroutines can't change that.
With virtual threads that synchronous api can be used at the performance level of what a hypothetical JDBC rewite would give.
(Not that you want to hit your DB that much, but you know what I mean. You don't need to specially wrap or bundle apis to get into an async call juggle.)
[1]: With one caveat: Libraries which call directly into blocking native calls do not become async automatically. But they are very rare on the Java platform.
If you are already using co-routines, there's very little you will need to do other than updating the library when they add the support for this. Other than that, it indeed already has essentially all of the feature set that Loom adds to Java. So, do several other frameworks like Spring's flux, vert.x, rx java, etc. Kotlin's co-routine framework actually has extension functions for all of these as well as things like threadpools, worker threads, etc. in Java.
The value of Loom is mainly adding low level JVM support for this. Other frameworks will evolve to use that as well. The Java API to this is probably not that interesting; even if you do use Java. You probably should be using something a bit higher level. There are quite many frameworks for Java implementing all sorts of ways to do the same things. All Loom does is add a few useful things for these frameworks to do their thing a bit faster.
Kotlin's co-routine library is actually a multiplatform library that works in natively compiled kotlin on IOS/linux/windows/etc. (and soon wasm), in kotlin-js in a browser or node.js, and in the JVM. On each of these platforms, it uses a platform specific implementation as well as ways to seamlessly interact with platform specific things (e.g. promises in a browser, futures, threadpools, spring fluxes, etc. on the JVM). So, how co-routines are executed and scheduled is platform specific. The resulting code tends to be very portable and look very similar. I actually maintain a few multi platform kotlin things that support co-routines and they work great on both the jvm and in a browser.
When Loom releases, it will just be yet another thing that co-routines can be executed with. On the JVM, you can trivially create a co-routine dispatcher from a thread pool. A co-routine dispatcher is basically where you schedule your suspend functions to run. Loom basically just provides alternate threadpool and thread implementations that follow the same API that use the underlying jvm functionality (which is the really interesting thing it adds). So, the changes for Kotlin's co-routine library to support this are going to be pretty minimal. In fact, a lot of its current extension functions should just work against the Loom API without any changes.
There's nothing in the Loom apis that is particularly interesting if you use co-routines but the low level JVM optimizations are of course interesting from a performance point of view. Also interesting is the improved ease of dealing with stack traces; which can be a bit of a pain point with co-routines on the jvm. So, lots of good reasons for Kotlin users to look forward to this but no big reason to wait for it. You can use co-routines right now and the same code will continue to work great when Loom gets there in an LTS version in a few years. But it might run a little faster and be a bit easier to debug.
While there's nothing wrong in using something higher level, the main reason for using higher level libraries are because using threads doesn't scale past a certain point.
The problem with libraries that try to work around the scalability issue is one of compatibility. Using co-routines is great, but you need workarounds when targetting JDBC or a Http client. You have to be using coroutines, or coroutine friendly code, everywhere, or you risk reducing performance.
For this reason, we just use regular threads and threadpools in our projects. Once Loom lands we'll change the executors to spawn virtual threads and then we'll be done.
That said, coroutines shine if you can't wait for Loom to land or if you're targetting something other than the JVM (like Android).
I've used co-routines with:
- spring flux
- hibernate & jdbc (not a problem, you just use your connection pool as usual and use a threadpool based coroutine context to ensure you don't block your asynchronous request handling main thread. You might prefer switching to some more modern versions of that that support asynchronous IO though. But that stuff is still relatively new and many people stick with blocking IO for this for now. Not in any way a show stopper for using co-routines.
- apache httpclient with synchronous IO and a connection pool (same thing basically).
- apache httpclient with asynchronous IO (very easy to integrate it's callbacks with suspendCoroutine { ... })
- redis (both synchronous and asynchronous)
- mongodb
- Java stream API (there are loads of Java libraries that use that)
I get it, some people don't want to switch language. So, stick with Java. But do it for the right reasons. Performance really isn't one. Anything Java does, Kotlin can do too. And generally about as fast by virtue of simply using the exact same things in the standard library. And generally without the boilerplate and a lot of syntactic sugar (i.e. it's nicer). Probably if the Kotlin version of something is slower than the Java version, it's because you are doing it wrong. I can't really think of a lot of cases where that would not be easy to fix.
I've seen my fair share of buggy Thread based Java logic over the years; trust me co-routines are way nicer than that. You can still get into trouble with them of course (and mostly for the same reasons). But it covers all the bases pretty well and generally does a better job of keeping you out of trouble.
There's only 1 co-routine related keyword in Kotlin: 'suspend'. The rest of co-routines ships in the form of a normal kotlin multiplatform library that you just add to your project. Java has several keywords that you don't need in Kotlin (e.g. synchronized, volatile). You can mark things as synchronized with a simple kotlin function. And likewise there's a Volatile annotation. Mostly that's just useful for kotlin code that needs to be used from Java.
The function coloring bit seems to obsess a lot of people. I just don't see the issue with it. For me the boiler plate that Java makes you use instead is a much bigger issue.
All of the parts that throw `InterruptedException` are handling the thread interrupt cancelation mechanism.
There is also the example with the atomic boolean quit flag.
I'm not convinced that Go has any unique mechanisms here. Just like Java you can't forcefully kill a thread without that thread's cooperation.
As much as I love Java (I co-founded Apache Java), golang is a great fit for this usecase.
Total boot payload is about 160megs... which I need to do some more work on... I think I can get this down to about 120megs, but it hasn't been a priority yet since this is working well enough for now. About 54megs of that boot is just some third party drivers and right now, those are .gz encoded... need to switch to xz to bring it down.
I presume it would have to be because there is no guarantee that the JVM will be installed and configured exactly correctly on all of those machines a priori.
Jlink helps solve that problem if you have a properly modularized project, but that's hard to do if your dependencies aren't also properly modularized.
The Go version needs that executable, nothing else.
It is a fresh language and i quite enjoyed exploring it, but i just can't see the use of it. (also, the multiple return value functions are great, but if only there was a way to use a particular value directly from the function without having to assign them to variables)
And I'm hardly a fan of Go.
There is room enough for both languages.
So all what left is opinionated in-language support vs library support, and it is not clear cut which is the winner. Java seems to allow finer control over the primitives of concurrency, so a library or another JVM language could build up a much better abstraction over the mechanism.
Still closer though, and GraalVM native images are pretty cool.
https://mail.openjdk.java.net/pipermail/discuss/2020-April/0...
Or as a type safe C for userspace.