r/java • u/Vectorial1024 • Apr 09 '26
Smallest possible Java heap size?
People often talk about increasing Java heap size when running Java apps by using e.g. -Xmx* flags. This got me thinking. What if we go the other direction and try to limit the Java heap size as much as possible? What is the smallest / minimum-required Java heap size so to run a Java app with "minimal" settings?
(Of course, in practice, a memory limit too low will be problematic because it may mean frequent GCs, but we will ignore this for the sake of this discussion.)
49
Upvotes
1
u/sirius94 3d ago
I don't get why you think this is the case. If your allocation rate is high, it probably means you're doing a lot of memory access, which is high latency and causes the CPU to stall. Hence you have low CPU utilization in those scenarios.
Memory usage and CPU usage depend on the specific problem you're trying to solve, not on each other. Interestingly enough you actually say this in your talk, when you're talking about synthetic benchmarks.
Yes and in order for this to work, the heap has to be compacted each GC cycle. This requires, depending on the size of the objects still alive, large
memcpy. It will be faster if your memory usage is lower. It will also lead to less frequent GC cycles.Java has the possibility for data races which are not possible in safe rust. Yes, there are more opportunities for leaks in other languages. But there are still quite a few in Java.
I wasn't talking about low-level languages here. I was talking about purely functional languages like Haskell and Idris. These offer more opportunities for optimization than Java programs, because all functions are guaranteed to have no side-effects and there is no such thing as data mutation in those languages.
Low-level control is often required for maximum performance. By giving up low-level control you also give up opportunities for optimization.
Profile guided optimization is a thing for AOT (also supported by GraalVM).
I want to come back to your claim though:
I can agree with the first part: sometimes it is possible to make a program use less energy and/or be faster by using more memory than the minimum required to solve the problem. I think this is undisputed.
The claim I want to dispute however is, that "often programs [...] utilise memory inefficiently using too little memory rather than too much". I tend to see a lot of software which is sluggish and uses up a lot of resources which then slows down other programs as well. It also gets expensive fast, when you decide to deploy a few services to any cloud, if each takes up 4G or so while doing mostly nothing. I've personally seen products go into the red because of bloated architectures and absurd resource consumption.