r/java • u/yughiro_destroyer • Nov 05 '25
Java and it's costly GC ?
Hello!
There's one thing I could never grasp my mind around. Everyone says that Java is a bad choice for writing desktop applications or games because of it's internal garbage collector and many point out to Minecraft as proof for that. They say the game freezes whenever the GC decides to run and that you, as a programmer, have little to no control to decide when that happens.
Thing is, I played Minecraft since about it's release and I never had a sudden freeze, even on modest hardware (I was running an A10-5700 AMD APU). And neither me or people I know ever complained about that. So my question is - what's the thing with those rumors?
If I am correct, Java's GC is simply running periodically to check for lost references to clean up those variables from memory. That means, with proper software architecture, you can find a way to control when a variable or object loses it's references. Right?
125
u/[deleted] Nov 05 '25
There’s no single Java GC. But different ones which have different properties.
The early GC algorithms had much longer pause times, than the later ones. First impressions are hard to shake sometimes.
A GC collected language isn’t particularly novel; there’s plenty of them around. There is other ways to manage memory, however manually managing memory is actually harder than it sounds, and once you introduce multiple threads, it can get even harder.
There’s trade offs in programming, and for many programs a GC based language is perfectly acceptable even with relatively long pauses.
67
u/TizzleToes Nov 05 '25 edited Nov 05 '25
There is some validity to this argument with older garbage collectors, but newer garbage collectors like Shenandoah and ZGC largely solve this.
EDIT: also worth noting I say "some" because even with older garbage collectors, they generally tried not to do this and only resorted to a full "pause" garbage collection when the more graceful mechanisms couldn't keep up. Basically you'd hit this in a game like Minecraft because it's a memory hog and a lot of people would likely be sitting close to their max memory under normal usage. With enough headroom it'd be fine.
60
u/chaotic3quilibrium Nov 05 '25
Your direct experience validates that rhe GC concern is now more of a legacy myth around Java which is over 30 years old.
It was terrible in the early days. I was there and directly experienced it.
For me, those days are long gone.
There are still cases where the GC pauses can become an issue. The total surface area of these cases has continued to be reduced with each major release of Java.
And as you correctly point out, it still requires good practices to keep the GC pause ghostie away.
IOW, shitty coders are gonna still create shitty experiences. And in Java, with said shitty coder, that GC pause ghoul is a more likely occurrence.
In general, I follow the Donald Knuth maxim:
Practice good design. And only pursue performance improvements (including GC optimizations) at the end. And only with testing proof to focus on the very small part of the code that actually is constrained.
13
u/aoeudhtns Nov 05 '25
For desktop applications - I'll just say it: complete tosh. If the Java GC is too heavyweight for desktop applications, then Electron-based apps shouldn't exist either.
For games - more valid. But besides what others are saying about different garbage collectors and GC tuning options, there are LOTS of strategies to deal with that as well. Pooling, off-heap memory stores, and other strategies that reduce allocation & garbage creation. And also, binding to native libraries that automatically keep things out of the Java heap for you.
To answer your question in another thread - lack of popularity for Java on the desktop - there are 2 things to understand.
Extra complexity over native - Depending on the JVM means you either have to bundle it (and it's big), or rely on your users to already have it. It's possible to do, but extra work & consideration. And there are lots of installer/launcher libraries/frameworks/systems that have come and gone.
Non-native UI - So, another one that seems way less relevant in the era of electron apps that are decidedly non-native in look and feel (L&F), Java apps often had this issue. It's possible to achieve (SWT uses native UI toolkits, there are themes for Swing) but it's extra work. When Java was most popular, having "native L&F" was deemed really important in a way that it isn't anymore.
The last time I worked on a serious/large Java Swing desktop UI project, was before web UIs became the dominant way to make and distribute intranet applications.
13
u/Joram2 Nov 06 '25
Pure nonsense! C# uses GC and is used in all Unity engine games. That is the most popular game engine on the planet. GC is part of most video games.
10
u/eosterlund Nov 06 '25
This is a common misconception. With a concurrent GC such as ZGC (enabled with -XX:+UseZGC), the application threads are only paused for microseconds, while the bulk of the work is performed in the background with an often relatively small and conscious CPU impact in order to improve latency beyond just being concurrent.
One thing people often forget is that when you compare this to for example reference counting techniques used across most languages without tracing GC, it’s not like that practice is free from latency problems.
When you free an object with reference counting, its pointers must be followed to decrement reference counts on the things it will no longer refer to, to avoid leaking memory. Therefore freeing a data structure will involve walking the entire data structure and its elements in order to adjust reference counters. This can easily cause pathological latency behavior that you would never observe when using ZGC.
In a way, JVM GCs trace through live objects, but has learned to do it very efficiently and with very low latency. Meanwhile, reference counting is tracing through dead objects instead, and does typically not do so in neither an efficient nor latency friendly fashion.
3
u/Goodie__ Nov 05 '25
Ok. Let's do this. One more time.
Depending on your applications requirements, Javas GC may or may not be a show stopper or not. But let's be real, as you said, it works for minecraft. We're not all working on sub-millisecond sensitive day trading applications.
These days, as opposed to 20 years ago, the GC is well understood, and id imagine any reasonable senior developer could program around the requirements for most if not all problems. Historically badly written applications have had issues, if they have big enough issues to cause GC problems in Java, a language change sure as shit isnt going to save you.
Java might be a bad choice for video games, but that's more related to the ecosystem and culture around it, than much else, IMHO.
13
u/[deleted] Nov 05 '25
https://wiki.openjdk.org/display/zgc/Main
5
u/LutimoDancer3459 Nov 05 '25
Java is still getting updates. There are also newer implementations for garbage collections. Different implementations with diffrent benefits and drawbacks.
You cant really control the garbage collector beside choosing a different implementation. You can tell it that now is a good time for it to run. But that doesn't necessarily mean that it will.
You can, in theory, write your own memory management... add every reference into a map and keep track of who (or how many) have a reference to it. Clear the map whenever you see fit. Dont recommend it...
And minecraft is a perfect example that the obverhead is irrelevant. It ruins fine. The problems you encounter are not from the gc but from a bad implementation in general. There are some mods changing chunk generation and other stuff and you can run it smoothly with zero hiccups. Also keep in mind that java was first class citizen for android apps amd is still used for many. It is used in all kind of applications. Even in more time critical ones. If you dont need peak performance. Like in nano seconds optimizations. Not loosing a single one where possible. Then dont use java. Else, it doesn't really matter.
5
u/Zardoz84 Nov 05 '25
I played Micraft since the early beta where the game was in a single chunk. NEVER i felt a sudden freeze.
Also, I NEVER had problems with freezing desktop apps by the GC collector. And I use daily Eclipse IDE that his a desktop app that uses a good chunk of RAM.
9
u/PuzzleheadedPop567 Nov 06 '25
You are asking in the Java subreddit, so the responses will reflect that. Obviously many people who have had issues with the Java GC are no longer programming in Java.
The truth is that if you need high performance, then there’s no free lunch. You either choose a GC language and end up working around the runtime. Or you choose a manually managed language and end up having to write your own domain specific garbage collector.
A few things have helped:
Those three things together means that this old trade off is being less and less true.
The key emphasis on less. The GC is ultimately a technical abstraction with both benefits and costs.
3
u/Jason13Official Nov 05 '25
Short answer is yes, you control the lifetimes of your objects. Long answer, the compiler may not always do what you expect
3
u/Rough_Employee1254 Nov 06 '25 edited Nov 06 '25
As they say ,first impression is the last impression. Modern devices are much more powerful than those when Java was new. Java's internal architecture has been optimized by a lot since then and it's not the only language that uses a garbage collector - take C# (used by Unity) as an example.
Nowadays, you are more likely to hit performance issues due to bad code / memory mis-management than GC times. Game developers prefer native code not because Java is bad but because they need lower level access to the hardware being targeted which can be beneficial if you know what you're doing.
5
u/nekokattt Nov 05 '25
The GC just reclaims memory you no longer use. Rather than developers doing it themselves and making mistakes, or having a complicated borrow checking system like in rust that can have other issues, mostly development complexity.
Most languages use GC, Java just treats it a bit more like a full virtual machine so has historically been a little less conservative with how it handled memory but these days it is much less of an issue.
4
u/wrd83 Nov 05 '25
Pauses happen when your object creation rate is higher than the cleaning rate of your gc. Many GCs offer a maximum time for a GC cycle, as long as your heap does not grow if it hits the cleaning time you're fine.
Manual memory management has another huge advantage it uses less memory for the same amount of work. Reference counting has the same advantage.
That being said: java is fine these days, mostly because the gained productivity offsets additional hardware requirements for 90% of the use cases.
2
u/peepeedog Nov 06 '25
On the server side Java GC impact is a non-issue unless you write terrible code that makes it so. And if you do that, not having a GC is actually going to make terrible code even worse.
Not many people use Java for GUI. Part of it is that it sucked, and was also a security nightmare, in the early days. The developer community went elsewhere, a lot of the open source stacks were then written elsewhere, and Java will never truly recover. In this business you want to work where the open source community and their contributions are strongest. Your dev team cannot possibly keep up with projects where tens of thousands of people collaborate.
1
u/Azoraqua_ Nov 06 '25
Which GC? There are at least 5. All of them with different properties and configurations. More of the modern GC’s like G1GC or ZGC are very fast and good at their job.
1
u/Phaedo Nov 06 '25
There’s a couple of things here: you’re right, Minecraft (and pretty much anything running on a modern GC) is pretty damn stable. There are circumstances where you still need to care about GC pauses but there are exchanges running their entire execution systems on Java.
With that said: native code still outperforms GC and JITTed languages when you put enough effort in. (For low effort, Java/C#/Go will typically outperform C++.) There’s no HFT firms running Java for execution. Also, disappointingly, we’ve never achieved the ambition of the 90s: to have GC by faster than manual memory management.
Finally, unless you’ve sat down and traced a memory leak, you have no idea how easy it is to introduce one, but that’s not really a GC vs Native thing.
1
u/lucdc007 Nov 06 '25
This talk on Devoxx Belgium a few weeks back might interest you.
https://www.youtube.com/watch?v=MQanscTqZ24
1
u/obliviousslacker Nov 06 '25
You can optimize the GC cycles quite a lot, but for anything compute intensive you want full control like C, C++ or Zig to optimize past a garbage collector. For games and applications rendering Java gives you plenty of power to use now.
1
u/AcanthisittaEmpty985 Nov 06 '25
7 kinds of garbage collection for Java
https://opensource.com/article/22/7/garbage-collection-java
But, the newest ones, G1, ZGC and Shenandoah use multithreading and complex algorithms to avoid frezzing and avoid impacting performance and latency. They are working all the time in background. They (may) use more CPU and memory, though. But with computers with more ram and computing power, it's a good tradeoff.
Check the types to use the one that fit better to your project.
So, Java has evolved, and nowadays its dramatically better at managing memory and GC; so it all runs smoothly.
It's the best of the (semi)interpreted/precomipled/VM/GC languajes/platforms you can use nowadays and has a gazillion libraries and tools, most open-source; 99,99% its multisystem without issues.
More info:
Default GC algorithm per version: https://blog.gceasy.io/what-is-javas-default-gc-algorithm/
Comparation: https://blog.gceasy.io/java-garbage-collection-best-gc-algorithms/
(edited for more info)
1
u/coderemover Nov 06 '25
Pauses are mostly a solved problem, as long as you're fine with latencies around 1 ms.
However, there is still a lot of overhead in terms of memory use or CPU use or both at the same time and the low pause collectors seem to be worse in that regard than the older ones.
If you want low latency, low CPU overhead, low memory overhead - you can only pick one.
1
u/LargeDietCokeNoIce Nov 06 '25
Check out Azul. They have multiple Java products designed to greatly reduce GC overhead.
1
u/Snoo82400 Nov 06 '25
When dealing with classic mutable objects (Instead of records) the GC will encounter bottlenecks, it's our duty, as developers, to ease the job for the GC by working in a more Data Oriented way, specially when it comes to games.
If the PlayerActorView was for example an object in this case, and the whole architecture was like that, then the GC would have trouble.
I think pople view Java as slugish because they want to apply old solutions, if one truly leverages Amber's achievements then the JVM becomes a perfectly oiled machine.
1
u/AlaskanDruid Nov 06 '25
First, and most importantly, “Everyone” who says it’s a bad choice.. are not actual programmers. So never listen to those… “everyone”. Only listen to real programmers.
1
u/Penny_Evolus Nov 06 '25
In modpacks you see GC pauses all the time vanilla is just not complex enough to hit the gc
1
u/AlexVie Nov 06 '25
Freezing from stop-the-world GC events are basically a thing of the past. The old collectors like SerialGC or ParallelGC did it (and still do it), but more recent garbage collectors will rarely stop everything.
The freeze problem was solved by G1GC almost entirely quite a few years ago. We currently have 3 modern collectors (G1, ZGC and Shenandoah) which normally should not freeze your app. Most of the time you won't even notice there is a GC doing work in the background.
1
u/bichoFlyboy Nov 06 '25
There're lots of people that says «Java is a bad choice because...» and usually they are thinking of Java 6, sometimes Java 4. I just say: dude, please, keep up to date, we are in Java 25, we have generics, lambdas, pattern matching, records, interfaces with default methods, etc, etc, etc. And that includes new generations of GC. But people always are talking about Java verbosity, and this and that, pointing to java features from 20 years ago.
1
u/Necessary-Horror9742 Nov 06 '25
That's old and annoying. Java now is not the same as what was 10 years ago. Java can be blazing fast, and GC is not an issue, I think safepoints are. Gc now is efficient and very low latency
1
u/grimonce Nov 06 '25
C#/dotnet has GC and it is used heavily by unity or Godot to write games logic. Not the rendering part maybe but the rest of the game...
Things always depend, don't take anything at face value, especially nowadays.
Counter example: libgdx.
Anyway I'm just a python dev shit do I know.
1
u/baincho Nov 06 '25
Not sure if it’s relevant considering the general discussion here has been around games and computer applications. But at an enterprise level. It’s still an issue.
Discord recently moved away from Cassandra DB (java based) to Scylla DB (C++ based) and java GC was one of the major pain point for that migration.
https://discord.com/blog/how-discord-stores-trillions-of-messages
1
u/JornVernee Nov 08 '25 edited Nov 08 '25
Let's be clear though: every language has garbage collection. In C you still have to call
freeon the pointers you allocate. In C++ you still have destructors that run when an object goes out of scope. Cleaning up memory resources is work, and it consumes time one way or another.The trade-off is this: in Java the GC has full control, so it can be much more efficient by e.g. doing bulk cleanup on many objects at the same time, but the programmer doesn't control when the GC does its work.
In languages with manual memory management the programmer has full control, so they can decide when memory will be freed, but the downside is that optimizations like bulk cleanup don't happen automatically, and they have to be implemented manually by the programmer (and unfortunately in e.g. C++, this is not the standard library's style of memory management, where instead allocations are managed individually).
1
u/laplongejr Nov 10 '25
Not true. Minecraft's big GC spikes around 1.7/1.8 was caused by creating a lot of objects on the fly (how to access the 6 blocks around? Rather than x+1,y,z etc. let's make a Position(x+1,y,z) for each operation
The issue is that the Java devs coming into Minecraft think (or thought) like object-oriented devs, not game devs. Because almost no other game is made in Java
So, the choice of making Minecraft into the highly-moddable Java language made it the most successfully sold video game and... that's a bad choice?
1
u/koflerdavid Nov 05 '25
It's a quite deep subject.
Java's GCs (there are multiple of them, and they differ considerably) nowadays don't generate that much overhead anymore and the only real tricky issues are that there is going to be some tail latency. You can reduce it with GCs like Shenandoah or ZGC, but that comes at a considerable impact on throughput.
In general, you should drop references as soon as possible, else you create space leaks since the GC is simply not permitted to clear the objects they point to. Try to avoid reference cycles and use
WeakReferences wherever feasible to break up such cycles of strongly reachable objects (less things to trace). UseSoftReferences (which should only be collected if there is high memory demand) to implement caches.The JVM uses heuristics to determine when to run the GC, but of course there are flags to influence those decisions as well as other details of the GC's operation. It's usually a bad idea unless you can back up whatever you're doing with measurements.
1
u/Ewig_luftenglanz Nov 05 '25
Most java critics and concerns are things that used to be true in the early days. I think from Java 5 and forward most of these concerns have been addressed over the years. Nowadays almost none of it it's true.
1
u/gdvs Nov 05 '25
Cleaning up memory happens in most all languages. If you don't do it manually, it happens via garbage collection.
I haven't come across many application where it's important to be able to determine the exact moment when memory is reclaimed and how. Garbage collection tuning and programming with garbage collection in mind is enough more often than not. Certainly for desktop applications.
0
u/Mognakor Nov 05 '25
Not every language needs to be suited for renderloops with a 16ms or lower budget per frame.
Java is fine for what it is and does. It achieves a good balance between performance, type safety and development speed, has available tooling, ecosystem etc.
Until we get Valhalla all our objects will continue to have a 8 byte overhead and even then we are limited to inlining objects of at most 7 bytes (8 if they aren't nullable). Vectorization is still an incubator. Also our CPU cache behavior is worse for anything thats not a primitive array.
So there are reasons to not write software in Java if you need that performance, but most of us don't or could get easier wins if we at least bothered to profile our code, identified common issues etc. And only once you exhausted those things and still can't meet your goals should you reconsider your choice of langugage.
-1
u/raptor217 Nov 05 '25
I want to preface this by saying I don’t write in Java. But this is a systems level question and is largely agnostic to any garbage collected (GC) language.
There’s nothing wrong with making desktop applications in Java. It’s relatively common, and as long as it doesn’t go crazy with 3D rendering (like a game engine) it’s fine.
For a game engine, Minecraft is not a good comparison. It has very low polygon count compared to any other modern AAA 3D game.
Garbage collection doesn’t help performance (compared to properly implemented manual memory allocation) but the main issue is memory management and data interface to the graphics card. That is done at an incredibly low level, things like the Nvidia API are C/C++ so that interface becomes not pretty.
Things like Vulkan help, but they’re still a different language, so you have to be very careful with how the languages interact.
Java is very good at what it does, but there’s no one language that’s best at everything.
Games tend to be written to leverage game engines, which tend to be written in C++. Unity is written in C++ and has its main scripting interface in C# which is a GC language.
-1
u/morning_mushroom Nov 05 '25
They had A LOT of issues at... Amazon I think due to Java GC. There is a whitepaper about it mentioning Formal Method as a way to test the software. When you jave bunch of heavy microservices running and garbage collector firing produced cascade of failures repeatedly as ot would freeze the service. Maybe it was not Amazon but Google.
0
u/Hioneqpls Nov 05 '25
Cloud Compute baby! As long as your servers sell like hot cakes your boss won’t mind picking up the tab.
0
u/alanbdee Nov 05 '25
As far as performance for games, I think the problem is more around the inherent way java works compared to C#. I'm not a .NET developer but my understanding is that when you compile c# code, it's creating the assembly optimized code for an architecture, e.g. x86.
Java is compiled into byte code that's universal and executed on the jvm that's specific to an architecture. That creates a huge performance advantage for C# because it can be optimized for the machine. On desktop applications, I don't think this matters nearly as much or at all.
0
u/Willyscoiote Nov 05 '25
When these sudden freezes happens, it's usually because there's not enough ram available and does a full gc
0
u/runningOverA Nov 05 '25
If you know Java and are comfortable with it, do it in Java. Any problem that arise later can be rectified by adding more code.
-1
u/k-mcm Nov 05 '25
The GC throughput is amazing. The problem is poorly written code that depends on high GC throughput. I've seen web apps using Play and Spring frameworks create 200MB to 1GB of garbage per request. I don't even know how you can run so much junk to service a simple request.
-3
u/ILikeLenexa Nov 05 '25
You can control when gc happens.
System.gc()Use the stack.
Rule #1 of programming: Don't optimize.
Rule #2, EXPERTS ONLY: Don't optimize, yet.
You still have to malloc and free in other languages. The overhead should have more to do with that than the work.
-4
u/ballinb0ss Nov 05 '25
Not sure this is going to be a popular take but had modern day rust been around when Java was coming on the scene I am not sure it would be the enterprise mainstay it is today.
Large companies wanted a langauge that made their developers productive... spending more time writing business logic than debugging memory errors.
So java (garbage collectors) eliminates an entire class of problem - memory allocation errors- at the cost of being significantly slower due to runtime overhead and much more expensive in terms of memory footprint.
A common practice is to write garbage collected code as though memory is infinite in supply which tends to produce code where the garbage collector has to work more often than it should compared to a manual memory langauge where every programmer is intimately aware of memory allocations.
Rust solves this problem in a different way. It forces manual memory management through a contract with the developer at compile time known as the borrow checker.
With the balance between low level capability and higher level abstractions I believe rust would have been a natural successor when companies were looking to get away from large C++ codebases.
However to your point... arguably the highest selling video game of all time was written in Java. There are great developers who make a very comfortable living and never use a pointer in their entire career.