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.

Sunday, 11 October 2009

Google Wave Robot - Twitter Wave Bot

Just a quick one.

I got my Google Wave invite the other day. I'm enjoying it, but it is a little bit too quiet for me to use productively at the moment. When I get some invites myself, I'll send them out to the people who've asked for them.

What I really wanted to post about was the robot I wrote. I was quite impressed by the easy of the API, and the integration with Google App Engine, which makes writing a robot really easy to do. My robot, Twitter Wave Bot, takes #hashtags and @usernames and simply links them up to twitter. It took me about 8 hours to implement and you can see the code here:

To get this robot working, add '' to your google contacts, and then add it to any wave and it'll start working for you straight away.