Tests for Memory Leaks in JUnit

Although Java features an automatic garbage collector automatically clearing up unused objects and therewith unused memory, memory leaks can occur (and do occur from time to time). This is often caused by ‘circular’ references between objects.

There are a few ways, to automatically test for memory leaks using JUnit. There seems to be an interesting method being part of the NetBeans framework assertGC() (see Tor Norbye’s weblog – How to write a memory leak unit test). However, this method is not easily available when working with generic JUnit. A generic approach is described in Palantir – Writing JUnit tests for memory leaks. However, both these approaches should be taken with a pinch of salt. They depend on the assumption that setting an object reference to null + calling System.gc() will actually ‘clean up’ the object, which is not to asserted in the JVM specifications.

Resources

Tor Norbye’s weblog – How to write a memory leak unit test

StackOverflow – Automated way to find JUnit tests that leak memory

Palantir – Writing JUnit tests for memory leaks

2 thoughts on “Tests for Memory Leaks in JUnit

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s