在 Java 中测试弱引用的正确方法是什么?
我最初的想法是执行以下操作:
public class WeakReferenceTest {
public class Target{
private String value;
public Target(String value){
this.value = value;
}
public String toString(){
return value;
}
}
public class UsesWeakReference{
WeakReference<Target> reference;
public UsesWeakReference(Target test){
reference = new WeakReference<Target>(test);
}
public String call(){
Target test = reference.get();
if(test != null){
return test.toString();
}
return "empty";
}
}
@Test
public void testWeakReference(){
Target target = new Target("42");
UsesWeakReference usesWeakReference = new UsesWeakReference(target);
WeakReference<Target> triggerReference = new WeakReference<Target>(target);
assertEquals("42", usesWeakReference.call());
target = null;
while(triggerReference.get() != null){
System.gc();
}
assertEquals("empty", usesWeakReference.call());
}
}
我对该方法的保留是使用 System.gc(),因为我知道它在不同的 JVM 上的行为可能不同。