Testing memory leaks with assertGC

I was talking about assertSize in one of previous entry about testing. NbTestCase class contains more useful methods. Today I will be talking about assertGC method. The assertGC method tests tries to run garbage collect with different methods and then scan if exists path to reference in memory by using insane library. Look at simple example:

public class LeakTest extends NbTestCase {
    
    public LeakTest(java.lang.String testName) {
        super(testName);
    }
    public void testLeak() {
        String obj = new String("test1");
        WeakReference ref = new WeakReference(obj);
        obj = null; 
        assertGC("pass",ref);
        obj = new String("test2");
        ref = new WeakReference(obj);
        assertGC("fails",ref);
    }
    
    public static Test suite() {
        TestSuite suite = new NbTestSuite(LeakTest.class);
        return suite;
    }
}

First asertGC passed because in JVM exists only WeakReference for object String("test1"). The second assertGC failed because the reference obj holds String("test2").

Comments:

Post a Comment:
Comments are closed for this entry.
About

xzajo

Search

Archives
« April 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today