views:

1040

answers:

3

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?

+3  A: 

I wouldn't say it's common - leaks are very rare in Java - but I've seen a leak due to keeping a reference to a non-static inner class which didn't use the outer instance, but held a reference to it anyway.

Pete Kirkham
Oh, I see this one happening fairly often if you're using the poor man's closures. You're not realizing that you're holding on to the outer object and all its references. This gets dirty *really* quickly.
krosenvold
+11  A: 

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.

Jon Skeet
A: 

PermGen leaks could happen due to:

  • Daemon threads which stay alive after you application is undeployed.
  • Shutdown hooks registered with the JVM
  • ThreadLocal variables where the value has a reference to a class loaded by your class loader

These are all web application related. They don't happen in standard Java applications.

coldeq