Wednesday, 28 October 2009

Weak References in Java

There seems to be confusion about when weak references should be used. I'm going to present two cases - the first one is when NOT to use them, then second case demonstrates what they should be used for.

Don't use weak references for listener management

So firstly - don't use weak references for handling 'listeners'. Say you have an object that allows listeners to be added to it, it may occur to you that those listeners might never get removed. The reason they don't get removed is :
a) because they aren't supposed to be
b) the programmer is lazy and/or doesn't understand 'lifecycle management'

It would be easy to think that storing the listener as a weak reference would avoid these potential memory leaks but what actually happens is that you introduce seemingly random behaviour to your application, since the listener could be garbage collected *at any time*.

The solution is - learn how to clean up after yourself.

Do use weak references for objects you don't care about

For instance, let's say your application exposes a front end to a database. The user is traversing your application instanciating objects probably based on data loaded from the database. In order to speed things up a little you might keep a handle to these objects for future reference, but actually you don't care if the object is available or not because you can reload it from the database as when it is needed again in the future.

What does that sound like ... that's right - a cache!

Weak references are ideal for this scenario.


No comments: