Search code examples
javamemory-leaksweak-references

WeakReference and memory leaks


I'm profiling my application using VisualVM and I see that the heap size increased by about 7MB in about 3 days. When I use memory sampler, I also see that java.lang.ref.WeakReference is in the top five for the instances number. The number of WeakReference is increasing and GC has almost no effect.

Any idea?


Solution

  • You do not have a memory leak.

    Java's GC only runs when the heap is full (actually is a bit more complicated since the heap itself is divided into generations, but anyway), so unless you are filling the heap (which is very unlikely since 7Mb is too little memory for any heap) you can't tell wether you have a leak or not.

    WeakReferences are small wrappers that actually help preventing memory leaks by marking the objet they reference as elegible for GC. My guess is that you're including some kind of cache library that creates a bunch of these, and since the heap still has plenty of room there's no need to garbage collect them.

    Again, unless you see that the GC runs often and your heap size still increases I wouldn't worry about memory issues.

    Here's a great article on this matter