Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Common Java memory/reference leak patterns?

Maybe the most typical example is the JDBC closing done wrong way and not handling the possible exceptions correctly. I am very curious to see other examples you have seen - preferably web application related.

So, are there any common leak patterns in Java?

like image 354
Petteri H Avatar asked Mar 22 '09 10:03

Petteri H


People also ask

What are memory leaks in Java?

A memory leak is a situation where unused objects occupy unnecessary space in memory. Unused objects are typically removed by the Java Garbage Collector (GC) but in cases where objects are still being referenced, they are not eligible to be removed.

Will there be a memory leak in Java?

In Java, the memory leak is a situation when the garbage collector does not recognize the unused objects and they remain in the memory indefinitely that reduces the amount of memory allocated to the application. Because the unused objects still being referenced that may lead to OutOfMemoryError.

How do you handle memory leaks in Java?

Use reference objects to avoid memory leaks Using the java. lang. ref package, you can work with the garbage collector in your program. This allows you to avoid directly referencing objects and use special reference objects that the garbage collector easily clears.


1 Answers

The two key "effective leak" patterns in my experience are:

  • Statics and singletons which gradually grow over time. This could include caches, poorly implemented and used connection pools, dictionaries of "every user we've seen since startup" etc
  • References from long-lived objects to objects which were intended to be short-lived. In C# this can happen with events, and the equivalent observer pattern could give the same sort of effect in Java. Basically if you ask one object (the observer) to watch another (the source) then you usually end up with a reference from the source to the observer. That can end up being the only "live" reference, but it'll live as long as the source.
  • Permgen leaks if you keep generating new code dynamically. I'm on rockier ground here, but I'm pretty sure I've run into problems this way. It's possible this was partly due to JRE bugs which have since been fixed - it's been too long since it happened for me to remember for sure.
  • Unit tests which hold onto state can last longer than you might expect because JUnit will hold onto the testcase instances. Again I can't remember the details, but sometimes this makes it worth having explicit "variable nulling" in the teardown, anachronistic as that looks.

I can't say that I've regularly found memory leaks to be a problem in Java (or .NET) though.

like image 129
Jon Skeet Avatar answered Sep 19 '22 21:09

Jon Skeet