More on swing garbage collection – static references

Static references are another common cause of memory leaks, both in Swing applications and other components.

If a static field holds a reference to an object instance, that instance will not be garbage collected until such time as its owning Class instance is garbage collected (which may be never). If have seen several applications which held Maps or other data structures at a static level, and over time the number of objects referenced by the collection gradually grew, resulting in a memory leak. Often items are placed in such collections without the developer realising that the item being added will never be released.

In many cases static fields are overused, and it is always best to question whether a field really needs to be static. When trying to find the cause of a memory leak, it is often a good idea to start by having a look at the tree of references which emanate from each static field reference, and see if this might be the cause.


You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

AddThis Social Bookmark Button

Leave a Reply