I have a java class that might allocate a lot of data.
I have written a junit test that should check for memory leaks similar to the code below.
Unfortunatley the test fails.
@Test
public void shoudNotMemoryLeak()
{
Runtime runtime = Runtime.getRuntime();
// make shure that gc has collected all
System.gc ();
System.runFinalization ();
// memory before creating my sut
long memoryUsedBefore = runtime.freeMemory();
long memoryUsedAfter = 0;
// this consumes memory
StringBuilder sut = new StringBuilder("hello world");
// make memory available to gc
sut = null;
// make shure that gc has collected all
System.gc ();
System.runFinalization ();
// memory after creating my sut
memoryUsedAfter = runtime.freeMemory();
// this fails
assertEquals(memoryUsedAfter, memoryUsedBefore);
}
Any ideas how to modify the junittest to check for memoryleaks?
[update]
unfortunatley the 9 year old possible duplicate did not provide a sulution to my question
I changed the title and content to make it more specific than the "possible duplicate candidate"