Thursday, August 12, 2010

CanonicalSet: Weak References from Set, Shared Instances

Today I needed to work with an approach that I think it's worth to share.

We were running out of memory issues due to many instances of a class. So I decided to make use of shared instances. Instead of creating the instance every time, it is better to check if it was created before and return it in that case.

In order to achieve that we have to have a collection for the objects we had created to check if it was created already.We need to put them in a set; however putting them in a set is a bit problematic: if we put them in a set there will be a strong reference from the set which prevents it to be garbage collected ever. We need a set which we can add objects with weak references so that if there are no more strong references from outside, it will be garbage collected.

Before starting development I goggled if it was already implemented. And of course it was:

You can download sources from and check it too.

Before this development; I had nearly 300.000 instances and now I have only 1040 instance. Of course you need to be sure that your object is immutable. Also be sure with your hashcode() and equals() methods.

The most notable method will be unique() method on CanonicalSet. Create your regular object and pass to this method. It will return you the one in the set if exists and drop the newly created object.

1 comment: