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.
I would start out by profiling your application and looking for memory hot spots by using the jvisualvm (part of the JDK). This will give you and indication of how large your objects are and what method calls are resulting in high memory use. It will also tell you how long your objects are haning around in memory which is generally a good starting point as you want to reduce scope to be as short as possible.
The next step is to identify commonalities in your objects either by refining your design or by implementing a cache. If you’re loading data from a fixed store then you could use softreferences so as the JVM runs out of heap these objects will be GCed (if your making changes to these objects you will obviously need to persist them before removing the hard reference). Then if they are needed again your application will simply need to reload them from the backing store (DB, files or whatever).
Make sure you know how GC works and understand your object references:
Here are a few good articles which explain references and GC:
http://www.java-tips.org/java-se-tips/java.util/using-weakhashmap-for-listener-lists.html
http://pawlan.com/monica/articles/refobjs/
http://www.kdgregory.com/index.php?page=java.refobj