1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.apache.commons.logging;
19
20 import java.lang.ref.WeakReference;
21 import java.lang.reflect.Field;
22
23 import junit.framework.TestCase;
24
25 public class LogFactoryWeakReferenceTestCase extends TestCase {
26 private static final long MAX_WAIT_FOR_REF_NULLED_BY_GC = 15_000;
27
28 public void testNotLeakingThisClassLoader() throws Exception {
29
30 PathableClassLoader loader = new PathableClassLoader(null);
31 loader.addLogicalLib("commons-logging");
32
33
34 Class<?> logFactoryClass = loader.loadClass(LogFactory.class.getName());
35
36
37 Field field = logFactoryClass.getDeclaredField("thisClassLoaderRef");
38 field.setAccessible(true);
39 final WeakReference thisClassLoaderRef = (WeakReference) field.get(null);
40
41
42 assertSame(loader, thisClassLoaderRef.get());
43
44
45 field = null;
46 logFactoryClass = null;
47 loader.close();
48 loader = null;
49
50 final GarbageCollectionHelper gcHelper = new GarbageCollectionHelper();
51 gcHelper.run();
52 try {
53 final long start = System.currentTimeMillis();
54 while (thisClassLoaderRef.get() != null) {
55 if (System.currentTimeMillis() - start > MAX_WAIT_FOR_REF_NULLED_BY_GC) {
56 fail("After waiting " + MAX_WAIT_FOR_REF_NULLED_BY_GC + "ms, the weak ref still yields a non-null value.");
57 }
58 Thread.sleep(100);
59 }
60 } finally {
61 gcHelper.close();
62 }
63 }
64 }