I have an application that works heavily with many custom objects that are created inside methods and never needed outside of them. The whole structure is (in my opinion) very good object oriented and uses Services, Utilities and a DI-Model.
Now, as I ran my first "large" tests, I quickly encountered OutOfMemoryExceptions. Now, I don't just want to increase the heap space and be done with it, as I can imagine that will not solve the problem but rather delay it until my application has grown more and encounter the same problem then.
I'm looking for some simple and easy to implement solutions, tips and snippets that help an application deal with garbage collection and heap spaces, especially when it comes to many loops that operate with object creation.
Something like "don't create objects in loops, create them before the loop and overwrite it within" and the sorts.
Some points:
The most important piece of advice that I can give you is the same as with any performance issue:
Profile, improve, repeat
Use a profiler (e.g. VisualVM) to find where the largest amount of memory is consumed. Improve your code, first to remove any memory leaks and then to reduce memory consumption in general. Repeat this process until you are satisfied with the quality and performance of your code.
EDIT:
A few tricks of the trade:
Share objects instead of duplicating, when possible.
Beware of the Java collection classes (i.e. the various Collection<T>
and Map<K,V>
implementations). Depending on what you are storing and what the collection in use is, you can easily increase your memory consumption by an order of magnitude without expecting it.
While Java does not (normally) have memory leaks in the same sense as encountered in C, Java code often has an issue with objects that are kept alive past their expiration date.
To avoid this, limit the scope of your references as much as possible or set them to null
when you are done with that object. Note: don't over do it with the null
-setting, especially in trivial methods that are expected to return soon.
Most importantly: make sure you remove an object from any collections it might have been entered into when you are done with it. Not doing so is a good recipe for an OutOfMemoryError
- and the most common cause of what people call a memory leak in the Java world.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With