12 ms·
Java garbage collection can be really slow
- gravypod 11y agoWas this done with the G1 garbage collector brought in by Java 7 if not this is worth a new test. It fixes a lot of problems that used to be introduced, and as long as you let it run wild with memory, and you are doing some parallelized work like everything real world, you should not see this problem. There should be either no more, or less, stop the world. There are a few things you can do to also avoid this problem all together: The biggest improvement in speed vs memory will come from not passing primitive as function parameters. When you are doing this, you are passing-by-value, not passing-by-reference. If you wrap a bunch of ints to a function that you are using you can save a lot of allocation cycles. Another good change that you can make would be an object pool. There is a really good and fast implementation in JMonkeyEngine/LWJGL. They have a low level, thread happy, object pool.
- needusername 11y agoSee the logs he posted [Full GC [PSYoungGen: 10752K->9707K(142848K)] [ParOldGen: 232384K->232244K(485888K)] 243136K->241951K(628736K) [PSPermGen: 3162K->3161K(21504K)], 1,5265450 secs ] -> parallel old A full GC frees 140k of old 1045k of young memory. He's almost running out of memory with parallel old. He needs to run a way larger heap. G1 isn't going to be any better with a live set the size he has in combination with his max heap. All this explained in Java Performance [1] http://www.amazon.com/Java-Performance-Charlie-Hunt/dp/0137142528 http://www.amazon.com/Java-Performance-Charlie-Hunt/dp/01371...
- polyfractal 11y agoJust a note, G1 probably still isn't ready for rock-solid production usage. E.g. bugs like this are still cropping up: https://bugs.openjdk.java.net/browse/JDK-8148175 https://bugs.openjdk.java.net/browse/JDK-8148175 That's a pretty scary bug. Who knows how stuff like that will trash your data if you aren't properly checksumming everything. CMS and other GCs have the advantage of years of bug-squashing and tuning. G1 is exciting, but I wouldn't personally use it on anything important for quite some time.
- gravypod 11y agoThat bug does not seem to effect Java 7, it only mentions 8u80 and 9. Still very bad though.
- polyfractal 11y agoYep, just more recent versions, and it's been fixed too. But if you watch the bugs that keep popping up for G1 you see stuff like this fairly regularly. Of course, that's a totally unfair comparison: CMS has had a decade of bug squashing...I'm sure it had equally scary bugs when it was new. But that's the point. Don't use new, shiny GC's because they are still squishing bugs :) (Sorry, preaching to the choir, I just get frustrated by everyone claiming G1 will solve all their problems without investigating potential downsides)
- needusername 11y agoActually CMS is only five years older than G1. The first published papers for G1 are from 2004. But yes, G1 has a long history of scary bugs. There was a time a few years ago where practically every week a crashing bug was fixed. G1 addresses certain problem areas of CMS and replaces them with others. Honestly I hope in ten years from now we have better choices in HotSpot than CMS or G1 but right now it doesn't look like it (if you don't count Shenandoah with has other issues). Having that said I have recently seen G1 performing exceptionally well in production: 120ms GC pauses with a 120 MB/s sustained allocation rate with basically default settings (apart from GC logging).
- kev009 11y agoIt seems semi-common to run HBase with G1GC now days.
- kleiba 11y agoYeah, I guess the first sentence in that article is spot on...
- pron 11y agoThis has probably nothing to do with GC tuning[1] or with Java's GC being slow (or any other GC), and most likely to do with either a bug in the program (a leak) or a misunderstanding of how the program uses memory. It's not the "GC ruining your day", but the GC not being able to fix a bug in your program and/or cram a 5 GB RAM usage into a 4 GB heap. [1]: Which is relevant if you're trying to turn a 100ms pause into a 15ms pause, or get rid of the 2sec pause you get once every few hours.
- kpil 11y agoThere is either a leak: The application keeps pointers to a lot of objects that are actually never going to be used. Or running out of memory: The application keeps pointers to objects that will be used later. Both problems are solvable, you remove the pointers or change the algorithm respectively. (If you simply can't add more memory.) The real hard problem is that the jvm takes a long time to report an OOM error. But it's not unique to java; Who have not seen servers that have become unresponsive in a low memory situation.
- needusername 11y agoSo yeah, parallel old has high latencies. In other news water is wet and the sky is blue. If you care about GC latencies don't use parallel old.
- PavlovsCat 11y agoSame for Javascript, at least when aiming for perfect 60FPS, the only good garbage collection is the one that doesn't occur after init, and maybe when switching maps or whatnot. Even the 0.09ms in the article is way too much and means a skipped frame. Maybe a way to think of it is to treat GC like optional automatic destructors, which should get called (more or less) when you want them to, not as something you just "don't have to think about" (if you run something in a loop and need it to be silk smooth, that is). Incidentally, this is great: https://www.mozilla.org/en-US/firefox/46.0beta/releasenotes/ https://www.mozilla.org/en-US/firefox/46.0beta/releasenotes/ > Allocation and garbage collection pause profiling in the performance panel
- ygra 11y ago> Even the 0.09ms in the article is way too much and means a skipped frame. He wrote 0.09 seconds. In any case, if you're generating megabytes to gigabytes of garbage in a single frame you probably deserve a GC pause.
- JoeAltmaier 11y agoIts very hard to control garbage. So many operations have unavoidable garbage side effects, especially involving immutable arguments.
- _ph_ 11y agoA good GCed language should give you good controls about garbage generation. If you have not these controls, the language is to blame, not the concept of GC. But indeed, I think one of the strongest disadvantages of Java is that it does not give you much control about garbage generation.
- whateveracct 11y agoWhat languages give you more control over GC than Java? My only experience is Java and Go. Go gives you literally one knob, whereas Java allows you to tune MANY factors on top of picking a collector.
- _ph_ 11y agoProbably a book needs to be written as in "Pragmatic Garbage Collection" summarizing some good practices to avoid surprises as the author of the article encountered. Having used Java since its creation and other GCed languages, I would summarize them as follows: - avoid allocating objects on the heap which you do not have to allocate. The less fresh allocations you have, the less the GC has to do. That does not mean you should write ugly and complex code, but if the tool described in the article was for example grep-like, then one should not have to allocate each line read separately on the heap just to discard it. If possible use a buffer for reading in, if the io libraries allow it. - generational GCs try to work around this a bit, as the youngest generation is collected very quickly, assuming the majority of the objects is already "dead" when it happens, only the "survivors" are copied to older generations. Make sure that the youngest generation is large enough, that this assumption is true and only objects are promoted to older generations which indeed have a longer lifetime. - language/library design makes a huge difference how much pressure there is on the GC system. Less heap allocations help, also languages, which try not to create too complex heap layouts. In Java, an array of objects means an array of pointers to objects which could be scattered around the heap, while in Go you can have an array of structs which is one contiguous block of memory which drastically reduces heap complexity (but of course, is more effort to reallocate for growing). - good library design can bring a lot of efficiency. At some point in time, just opening a file in Java would create several separate objects which referred to each other (a buffered reader which points to the file object...). My impression is, "modern" Java libraries too often create even larger object chains for a single task. This can add to the GC pressure. Of course, all these practices can be used equally "well" to bring down a program with manual allocation to a crawl. So in summary I am a strong proponend of GC, but one needs to be aware of at least the performance tradeoffs different factorings of one program can bring. Modern GCs are increadible fast, but that is not a magic property.
- Peaker 11y agoGreat comment. I disagree about manual memory management though, you don't have to traverse the heap, unless you use a semiautomatic scheme like reference counts. Complex heap structures often aren't a problem for manual memory management. The scenarios that kill GC aren't ones you typically worry about in manually managed code. GC frees you from some concerns and gives you much safety but makes performance harder and less predictable. For many programs this is a good trade off.
- sdesol 11y agoI actually wrote a blog on how I keep an eye on JVM garbage collecting at http://gitsense.github.io/blog/realtime-process-monitoring.html http://gitsense.github.io/blog/realtime-process-monitoring.h... My indexers are designed to automatically shutdown, if they are spending more than 30% of their time doing garbage collecting, in the last 10 minutes. If they shutdown on purpose, my background Perl script will restart them. However, if they shutdown X number of times in a row, my Perl script won't restart them. Multiple consecutive shutdowns, usually means I'm pushing the system too hard and I'll need to tweak my indexers thread settings.
- pjmlp 11y agoCorrection, a specific GC implementation, of a specific Java implementation can be really slow.
- rootlocus 11y agoOn a specific, memory-leaking, use case.
- fpoling 11y agoThe old rule of thumb is that with GC one needs at least twice the memory than the max live heap. With little free space GC disables a lot of possible optimizations that bigger free space allows. Another Java-specific rule is that with heaps over 1-2GB one must think how to make data structures GC-friendly or how to split the application into separated processes. I guess the example program violated both of these.
- matt2000 11y agoThis is probably the wrong title for this article. In the article she gets right up to the available memory limit and keeps trying to allocate more, the VM is forced to work increasingly hard to find the memory requested. I wouldn't call that slow GC, just trying to use too much memory.
- askyourmother 11y agoGarbage collection can cost money to a firm. Working a few years ago in a large investment firm, lots of the code used to trade via algos, make markets, index arb, was all written in C++. Deterministic, performant, reliable - it just worked as planned and expected. New tech lead comes in, swaggers about, declares all the street now uses Java for their trading code, we should too. I got the desk heads to listen and be wise to the impending issues, and they told him fine - but if the new Java based code had direct impact on PnL, then his budget, ultimately, he would pay for it. Cocksure, he agreed. Despite throwing bucket loads of Java devs at it, spending fortunes on "tuning" consultants, performance suffered, GC did affect at critical trading conditions, and eventually he was exposed and kicked out. The C++ code came back out of retirement, was updated for C++11/14, and still serves them well to this day.
- hga 11y agoDid he try Azul's Zing or their previous Vega hardware solution for pauseless JVM GC? Not free by any means in $$$ or performance, but they should have avoided any pauses due to GC.
- realo 11y agoDo you actually mean that I need an expensive, dedicated hardware accelerator to get Java's performance to match C++? Why not do as they actually did: use C++ ? Sounds simple enough... and much cheaper.
- egwor 11y agoA few things to consider: * it tends to be harder to write good C++ code than Java. For example we think that an average person can write better java code than C++ code because java is simpler to get going with. We also think that the average developer makes fewer mistakes in java than C++ (because C++ allows you to do 'crazy things!') * that means that you need (on average) a better developer for C++, and that tends to cost more * java tooling is exceptional (probably the best there is?) * making small changes and releasing is much quicker in Java; builds tend to be shorter in duration for example * once you have the framework for your system, the differentiator is then the business benefits delivered. If you can push small changes out very quickly you're getting rewards quicker and you can experiment more * once you get down to certain performance points, it becomes similar writing java code as writing C++ code, but the JVM is also doing various work that you can't control so much. That can then inhibit you. Other things: * Azul isn't just h/w development it's also now in kernel plugin form iirc * Have a look at Aeron (https://github.com/real-logic/Aeron https://github.com/real-logic/Aeron) and I think the C++ and Java versions are fairly similar performance and they're designed by super with decent (industry renowned) developers writing it * A lot of people write high performance code making extensive use of templates. That's a totally different way of programming than usual C++
- smegel 11y agoI wonder if Go's GC would exhibit pathological behavior in this case.
- Jabbles 11y agoGo's current garbage collector isn't generational. And it aims to complete its stop-the-world phase in < 10ms, so even the young generation collection which the author describes as "fast" would be unacceptable (90ms).
- deleted 11y ago[deleted]
- naranha 11y agoTldr: if you allocate nearly all heap memory, GC performance is bad. Who would have thought. What an insightful post.
- loevborg 11y agoThe article may not be news for you, but it doesn't pretend to be a comprehensive guide: it introduces common issues and explains their relation through an experience report. We do need to talk more about garbage collection. Many developers do not understand very well how GC works, and there's a lack of high-quality discussion online. The article and the discussion it's sparking helps demystify the topic.
- naranha 11y agoI agree. It has a very click-baity title though. From my experience GC is usually very fast, except when the program runs out of memory or over allocates all the time due to bad programming.
- DonPellegrino 11y agoThe point of the article was to show how the % of used memory will affect performance in a non-linear manner. It's obvious once you know, but it's not if you've never experienced it before.
- dang 11y agoPlease don't post snarky dismissals to Hacker News. It degrades the community. If you have a substantive criticism to make, please make it neutrally, so those of us who don't know what you know can learn something. Putting others' work down distracts attention from the subject matter, makes you sound like a jerk, and makes HN a bad place to be.
- Annatar 11y agoIf one has to worry about allocating or not allocating objects on the heap, what is the difference between worrying about memory management that way (and suffering memory consumption and performance because of the garbage collector), and doing memory management manually with alloca(3C) or malloc(3C) in C, and having pretty much guaranteed performance???
- panic 11y agoWell, when you use a GC, you don't have to figure out where to put the "free" calls. This sounds like a minor thing, but it lets you write code in a very different style (have you ever tried writing a functional program with explicit malloc and free?) That said, there are other ways to avoid writing "free" than using a garbage collector. Regions (https://en.wikipedia.org/wiki/Region-based_memory_management https://en.wikipedia.org/wiki/Region-based_memory_management) are faster at allocation than malloc (you just increment a pointer to allocate) and faster at freeing than a GC (you throw away the entire region when you're done with it). It seems tricky to base a general-purpose programming language around them, though.
- Annatar 11y ago> Well, when you use a GC, you don't have to figure out where to put the "free" calls. That is precisely why I mentioned alloca(3C): it automatically frees the memory for you, if you do not want to do it yourself. From the Solaris / illumos alloca(3C) manual page: void *alloca(size_t size); The alloca() function allocates size bytes of space in the stack frame of the caller, and returns a pointer to the allocated block. This temporary space is automatically freed when the caller returns. If the allocated block is beyond the current stack limit, the resulting behavior is unde- fined. > (have you ever tried writing a functional program with explicit malloc and free?) I got my start on MOS 6502 / MOS 6510 / MC68000 assembler, so for me making malloc(3C) and free(3C) calls when programming in a functional style is completely normal. I have no problem with that whatsoever.
- panic 11y ago
- cmrdporcupine 11y agoMy experience writing an bidder for realtime ad exchanges in Java -- which was a mistake driven by our use of some 'legacy' code -- the numbers work out on average but not in the 90+th percentile. Heavy tuning of the GC yields better results but there's always something that comes along and causes burps. Throughput is usually on average fine -- but the latency spiky. If your problem domain is fine with that, that's great. But I will never use Java for something latency sensitive again. After I left that job I worked on the other side of RTB, on the exchanges themselves. They were both written in C++, and performance was reliable and awesome. I would only use something like C++ or Rust for this purpose.
- poooogles 11y agoWere having a lot of success with our RTB app being written in Go. All we've done is tune the back pressure on the GC up so we trade off some memory for less GC time.
- jstimpfle 11y agoPlugging my own follow-up: https://news.ycombinator.com/item?id=11555129
- _ph_ 11y agoA very good post, but like much discussion here it turns into a comparison of Java vs. C++. It would be good to also compare to Go, which is GCed, but gives you all the value types of C++. The value types of Go are probably the reason that they have so good GC performance (version 1.6+) without all the complexity of the hotspot GC.
- stevesun21 11y agoYou can write Java code to skip GC and manage memory by yourself. Like C++ http://www.mkyong.com/java/java-write-directly-to-memory/ http://www.mkyong.com/java/java-write-directly-to-memory/
- fauigerzigerk 11y agoIt's nothing like C++. In C++ you get automatically managed memory on the stack. You get RAII and smart pointers to help with heap allocations/deallocations. Most importantly, you get to _use_ the system's malloc implementation whilst you have to _implement_ your own malloc with the Java off-heap solution you suggest.
- stevesun21 11y agoI'm not a C++ expert, RAII sounds to me is like a synchronous GC in C++ -- resource auto alloc and dealloc by it's lifetime (https://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization https://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initia...), correct me if I am wrong. Java, in another way, it has an asynchronous GC -- use different generations, and not release object right away just because out of scope. Anyway, I am saying 'like C++', I meant the possible way C++ can manually manage the memory directly, learnt from what you mentioned, I should say: 'like C'. Thanks.
- catnaroek 11y agoRAII is an automatic memory (more generally, resource) management scheme, but it isn't garbage collection. A garbage collector is a runtime component that reclaims unused storage. What RAII does is, at compile time, insert the appropriate resource-freeing calls at the right places.
- fauigerzigerk 11y agoThe problem with Java off-heap designs compared to C is that many Java language features become useless (e.g. instance variables, polymorphism, ...) and you lose the standard library as well as almost every single third party library out there. In my view, sun.misc.Unsafe is extremely unproductive to work with. But I will say that it may be the right solution for adding a small very spcialized feature to a larger Java application.
- stevenh 11y agoI had to solve stop-the-world pauses that were causing occasional intolerable lag spikes in a multiplayer game. The solution was to switch to Java's G1 GC, and also to deadpool and reuse every object and byte array I possibly could.
- jkot 11y agoIn my experience there is usually one or two collection which consume most memory. It is easy to solve 90% cases with a few simple optimalizations.
- rootlocus 11y agoHere is a pretty comprehensive article on the java garbage collector: https://plumbr.eu/handbook/garbage-collection-in-java https://plumbr.eu/handbook/garbage-collection-in-java that has helped me a lot. It touches the basic aspects of garbage collecting, and dives into the different kinds of GC available for java at this time.
- known 11y agoContainers will slow down your app
- simula67 11y agoThe problem is not just with the time it takes, but that most garbage collection algorithms are stop-the-world ( not sure if any of them are truly concurrent ). This can introduce correctness problems. I used to work on a network management software that used ICMP polling to detect if network devices were down. We had a SEDA architecture, requests were put on a queue, timers were set and if the device did not respond within a timeout, we would mark the device as down. Problem was, it so happened that in a high load system after we sent out the request, the garbage collector would kick in and take eons to return the system to running state. When the system returns, the timer events would fire and the handlers would note that the timeout has expired and mark the devices as down. The device could have responded in time to the requests but the system would not have detected it. This is why I am weary of languages with mandatory garbage collection. I feel it should be a library in any serious systems language.
- hga 11y agoSee https://news.ycombinator.com/item?id=11555017 https://news.ycombinator.com/item?id=11555017 Azul's Zing is pauseless, never has to do a stop-the-world collection which they say on a JVM takes about a second per GiB. It has threads which concurrently collect as other threads mutate, uses clever VM tricks such as bulk operations with only one TLB invalidation (or at least they did that with an earlier version of the current collector, they couldn't get it into the mainline Linux kernel and now use a DLKM). It's the only non-toy currently maintained pauseless/concurrent GC that I know of.
- guipsp 11y agohttp://openjdk.java.net/jeps/189 http://openjdk.java.net/jeps/189
- Roboprog 11y agoI forgot the exact number, but I remember reading somewhere that for a garbage collector to work well you need to give it something like 3 or 4 times more space than you will actually be using at maximum allocation - not counting transient stuff. This allows it to shuffle things around more effectively while it is cleaning up, doing things like copying into a compacted area.
- wmccullough 11y agoIn other news, the sky is blue.
- dang 11y agoComments like this break the HN guidelines. Please post civilly and substantively, or not at all.
- recivorecivo 11y agoCan you make it part of the guidelines to not use ego? Without ego, comments contain substance and are civil.
- dang 11y agoThat might be setting the bar a little high.
- based2 11y agohttps://www.azul.com/products/zing/pgc/ https://www.azul.com/products/zing/pgc/
- stevesun21 11y agoYou reminder me the time that I worked in a biology project 2007, I developed a program with Java to analyze DNA sequences, every execution it can easily handle over 3GB DNS sequence file without any issues, but for just curiously finding out how fast the process can be, I rewrote the program with C. The result is that C one is about 3 times faster than Java one, but the dev C one costed me about whole week (2 days for Java one).
- pjmlp 11y agoWe have a few healthcare customers on our portfolio, except for the usual HPC research use, everything else on their daily tools is a mix of R, Java and .NET tooling.
- gozur88 11y agoThat's why in practice Java programs tend to be faster if the application is nontrivial. By the time you've finished the C version you would have completed the initial version plus a few performance tuning cycles had you written it in Java.
- geodel 11y agoI think at this point it is clear those who care about memory usage and deterministic performance will use C/C++/Rust(maybe). Saying Java is not up there will bring Java supporters arguing endlessly how Java is so superior to anything else in market, how Java's GC is state of the art. It would not matter to them how much expert level tuning it takes to make it work. Yeah and then there is Azul zing: a heavily over provisioned system on top of already over provisioned Java systems to have better GC compared to Oracle/OpenJDK GC. Working in Java for 10 years make me realize that so many solutions Java/ JVM ecosystem provides are to the problems that Java ecosystem created in first place.
- pjmlp 11y ago> Working in Java for 10 years make me realize that so many solutions Java/ JVM ecosystem provides are to the problems that Java ecosystem created in first place. There are lots of companies making a living selling tools to track down and fix memory corruption issues in C and C++. Java is not alone.
- mbfg 11y agoThis article would have been much more informative had we seen the actual program. Usually it doesn't much matter how big a file you read from your program assuming you are reading for aggregation purposes. If you are in need of individual records, then that is what databases are for. So i smell a large red herring. Is GC a problem? sure it can be. Usually tho when it is, it's more likely to be my problem, not the JVMs.
- rmprescott 11y agoTwo simple suggestions: The author mentioned reading in files with x "number of lines". If they are then parsing the lines into some structured format, there are likely many opportunities to look for low cardinality aspects and to reduce object tenuring by pooling strings using either String.intern or a hashset. They should also consider increasing the eden size.
- beachstartup 11y agoit's been a really, really, long time since i've read something about computers and been completely and utterly baffled by what i saw. thanks for making me feel young again.
- merb 11y agoDo you really need to read all the 8 million lines into memory? Wouldn't it be better to have some kind of streaming and read up to, do some work, read the next??
- jstimpfle 11y agoWhy not just assume so? Aren't there valid reasons to keep all in memory?
- karianna 11y agoDisclaimer: I'm the CEO of jClarity who produces Censum. For those who are looking to read the arcane output of a Java GC log, you can grab a 7-day free trial of Censum (https://www.jclarity.com/product/censum-free-trial/ https://www.jclarity.com/product/censum-free-trial/) - it parses GC logs (Java 6-9 all collectors) and gives you a host of analytics and graphs to help you figure out what's going on. We've also got blog posts on GC (https://www.jclarity.com/blog https://www.jclarity.com/blog) and our slideshare http://www.slideshare.net/jclarity http://www.slideshare.net/jclarity
- sjmaple 11y agoDisclaimer: I don't work for jClarity who produces Censum. This is a super valuable tool, which I recommend people take a look at should they have the misfortune to need to read a Java GC log. Great work, jClarity!