119 points · by ejboy · 2w ago · 83 comments
1. Default heap size varies: it can be 50% of the available memory for any amount of available memory up to 256mb; ~128mb for anywhere between 256 and 512; and then 25% for anything above 512mb;
2. The JVM will still do parallel threads even when CPU limit is 1,000 or below , which triggers CPU throttling much faster. Threads such as GC (even when it is SerialGC), ForkJoin pools, Database connection pools, HTTP server, and so on.
3. The JVM behaves MUCH better with 2,000 or more milicores, and a well sized heap. Having very small containers and dozens of replicas is worse than having slightly bigger containers (cpu/memory limits) and fewer replicas, even with a different ratio (e.g. 6 replicas will perform worse than 3 replicas, even when aggregated CPU and memory limits are the same).
I've been advocating on this for years [1].
It's been an amazing journey exploring JVM on Kubernetes: all that research is being turned into tools and products, if you are interested! One is https://aka.ms/jaz (not open source at the moment, but it is free), and https://brewlet.sh (MIT).
Google term: "-XX:+UseContainerSupport"
Having used Java since the days where you needed to do very heavy tuning to get it to run properly, it all seems alien, as understanding the old garbage collectors was basically mandatory 20 year ago. But even if you reply to someone that does understand the new features, you might be helping a bunch of people that don't. In my unit of about 100 programmers I am the only one that even bothered looking, given how every single pod we deployed was either completely unconfigured, or so badly misconfigured, using settings that haven't been ideal since Java 6.
In one of the pods, running a batch job that was using way too much memory, about a third of the memory in the old generation were millions of copies of the very same string. Interning of strings loaded like that has been a JVM option since 2014.
The Redhat image distros, like UBI and the JDK ones, have a really handy bash script, "run-java.sh". It's a wrapper script for best-practice and intelligent JVM runtime args inside of container envs:
/opt/jboss/container/java/run/run-java.sh
It started life as fabric8's run-java-sh, and it's what the Dockerfile.jvm generated by Quarkus apps uses as its entrypoint.The script handles, among other things:
- Heap sized as a percentage of the container's memory limit via -XX:MaxRAMPercentage (default 80%, compared with JVM's default of 25%). Tunalbe with JAVA_MAX_MEM_RATIO env.
- -XX:+ExitOnOutOfMemoryError, so an OOM kills the container and your orchestrator restarts it
- Defaults for GC and metaspace
- JAVA_DEBUG=true / JAVA_DEBUG_PORT=*:5005 turns on JDWP without you having to edit the Dockerfile
- http_proxy/https_proxy/no_proxy env vars get translated into -Dhttp.proxyHost etc
That said, this only makes the HotSpot JVM use cgroups data to interpret CPU and Memory limits. It does not make any special consideration of default ergonomics (thread pools, GC selection, heap sizing, and so on). Before the container awareness support, the JDK would read the VM/bare metal data; in other words, pre-container awareness support would result in this: if the VM has 32GB of RAM and a container is set for 4GB of memory limit, the JVM reads the 32GB as available memory.
All the defaults I mentioned still apply even inside a container.
Edit: no worries! thanks for sharing!
The OP undoubtedly knows this, whoops.
and I also read it not as contradiction but simply as useful additional information.
But if you've not already looked at it for your usages, I suggest people check out both the parallel collector and ZGC. ZGC in particular has been getting a lot of very nice features. Semi recently getting fast heap freeing (to the OS). The parallel collector for small heaps can generally beat G1 pause times.
Where G1 really shines over the parallel collector is the fact that it regularly collects old gen. If your app has a lot of caches, then G1 is very good at keeping the VM from ending up with very long pauses.
They should make get.java point to the download page. Oh and docs.java would be very cool!
The website seems to address how things are moving fast now in the age of AI. I mean using AI to find security vulnerabilities.
Serial will be your best choice if your app is constantly using 100% of that core or if you need to minimize the amount of memory overhead.
G1 is a better choice if you can be flexible with your memory and if you have a lot of periods in your app where it's below 100% CPU usage (maybe a lot of IO).
I don't think this is true.
Setting your CPU limit to 1 in Kubernetes does not mean the container sees a single logical processor. It only means the kernel allows it to use 1 core worth of CPU _time_.
If your k8s node is an 8 core node, Java will still see 8 logical processors. It just means you can only use 1/8th of each, or all of one, or some combination in-between.
I've never seen a k8s node running on a single core VM, as most of the cloud providers only use these for their free tier or shared core VM's for the lightest of light workloads.
that's incorrect, the jvm has been container aware for nearly a decade (https://bugs.openjdk.org/browse/JDK-8146115)
you are correct about the underlying scheduling. limits don't pin you to a core, you get quotas across all available
https://kubernetes.io/docs/tasks/administer-cluster/cpu-mana...
I have also seen customers wasting resources across Kubernetes because their developers would eventually tune JVMs with lowercase `-xmx` flag, which the JVM ignores, and thus by default, the JVM only sets heap size to 25% by default (for => 512mb of available memory).
edit: looks like you probably mean sth like this: https://openjdk.org/jeps/8359211
One great feature in Go (or Python, or Node JS) is that you don't have to care about setting the -Xmx. The runtime will just use more RAM as needed, and you can use normal mechanisms like cgroups to limit the maximum size.
The `.zip` gTLD set a really bad precedent.
Moving GCs free you from the high overhead of malloc/free runtimes, something that us old C and C++ programmers have had decades of experience with, and why our colleagues developed large, complex runtimes such as TCMalloc and jemalloc to remove some of that overhead, even though not nearly as much as moving GCs do.
The reason low-level languages don't use moving collectors despite their superior efficiency is because they must give up on some performance optimisations for the abillity to interact with the hardware or OS directly, and that means that pointers must be stable machine addresses (this is why you need a richer FFI layer in Java). Moving collectors work in many ways like arenas. They don't need to maintain free lists whenever an object is allocated or freed (in fact, they never free any object at all), and memory is freed in bulk. This is not the only performance that low-level languages leave on the table because above everything else they must be low level.
Every single language that can use moving collectors does (it's also a matter of resources; moving collectors are hard to implement, especially the modern pauseless ones).
Sadly, people who are not compiler or memory allocator engineers don't know that, so they believe "popular wisdom" disseminated by other non-experts.
P.S.
Re AI: It's certainly possible that AI will be able to write good, efficient, large software some day, perhaps soon, but if it's able to perform the global program transformations required to replicate the optimisations of a moving collector without one, it won't need the simpler and more local optimisations done by a compiler, and will be able to work better without one, directly in machine code, in which case all compilers and programming languages are also done. In other words, moving GCs will not be a relic of the past before compilers are (or maybe roughly around the same time).
Nonetheless, the title of the paper by Andrew Appel (Garbage Collection Can Be Faster Than Stack Allocation) was just a false statement, which today would be called a clickbait title.
No method of dynamic memory allocation can be faster than stack allocation, if the latter is done correctly.
In Appel's paper, he claimed that if you have tons of memory, than the overhead of freeing memory by the garbage collector can become low, because of its laziness, i.e. the garbage collector will be invoked only when there is a huge amount of memory that must be freed, so the overhead per freed byte will be low, even lower than when stack-allocated memory is freed word-by-word.
However, this comparison is a classic example of a straw man. When memory is abundant, many compilers implement an optimization where stack deallocation is delayed as much as possible, in order to free with a single instruction large amounts of memory. So the same lazy deallocation strategy is also available for stacks, and the difference between a single instruction needed for stack deallocation and a long procedure needed by the garbage collector is enough to ensure that for any realistic amount of available memory, stack allocation is the most efficient.
Obviously, stack allocation is not applicable to everything, which is why other techniques, like reference counts and garbage collectors, are also necessary.
But, this is only assuming we use only the most naive allocation algorithms when managing memory. Yes, it’s true allocating is faster with a GC than malloc. But then you have to remember - most GC languages force way more allocations than necessary. Java is perhaps the worst about this, where almost everything goes on the heap.
You can use arena allocators to put objects close together and get allocations almost for free. And, you can put more objects on the stack next to each other, avoiding allocation cost altogether. In practice, this will greatly outperform a GC, even if you don’t take into account collection cost! What will not outperform a GC is doing a million tiny allocations.
But, in languages like C and C++, you don’t typically do that. A million tiny allocations is a Java thing. That’s why when people compare runtimes they sometimes mess up. Yes, if you implement a Java algorithm verbatim in C++… it will perform poorly. So, don’t.
Also, moving GCs only perform adequately when memory pressure is low. The more memory usage and churn you have, the more moving, compacting, and collecting you have to do. The same is not true of other allocation techniques. A lot of comparisons are not well thought out because they’ll be running at 10% heap utilization. Of course that performs well, it’s likely the GC isn’t even performing many collections. But that’s not true at 90% utilization. Hence why collectors like the G1GC were historically disabled on memory constrained environments.
As for performance differences in practice, it is easy to encounter Java programs, typically either large ones or very concurrent ones, that easily outperform C++ programs by a factor of two or more, just as it's easy to see examples of the opposite, typically in smaller or less concurrent programs. This is what we would expect.
As experienced low-level programmers know, it is quite easy to avoid the operations that are slow in C++ or other low-level languages - heap allocations and dynamic dispatch - when programs are relatively small and/or young. As programs grow larger, it gets more and more expensive to do this because these operations offer high abstraction, the ability to keep changes local. And it is these two operations that the HotSpot JVM was built to optimise.
I gave a talk about exactly that at the last Devoxx: https://youtu.be/vhDwy1eCXbs
This is true of your basic moving collectors. It's generally not true of reference-counting collectors (including Bacon-style cycle detecting collectors). It's also not true of tracing collectors that have a step of sweeping all live and dead objects, such as mark-sweep or mark-compact.
GC is not memory efficient.
If a primary concern is optimizing memory usage, you will avoid GC languages.
You are right, though, that in a very memory-constrained environment, usually embedded devices, you may want to lower memory consumption regardless of anything else, and in such environments moving GCs are probably not what you want (although other kinds of GC could be).
More here: https://youtu.be/xr73mR7ii9M
Rust is not the silver bullet its community is trying to meme it into being. Its approach to memory allocation only works in some cases, the rest of the time you're back to refcounting and the potential for leaks.
For AI it's especially bad because they never memorize full codebase context in the way an experienced dev would, so it all becomes very dependent on how your codebase is structured and how you prompt it. GC just eliminates all those bugs and the associated token cost of trying to find and fix them.
Unless you want AI generated code to be single threaded and not take advantage of multiple cores, some form of collector is still required. If you want to avoid heap fragmentation issues, a compacting collector is generally recommended.
Now, free/Drop/etc. the root a tree of 100k nodes. That's a pause.
I wouldn't say so. An implementation of the free function could do batching of this kind internally.
Hobby and domain specific languages may still use GC but getting rid of the concept of GC is the right direction, along with removing different ways of doing things in a programming language. Go was right when it forced developers to use only pattern for loops, one pattern for error handling, etc.
I don't think that making programs a lot more complicated because they have to prove a very specific memory management discipline is the right way to go.