在Java中測試弱引用的正確方法是什麼?測試WeakReference
我最初的想法是做到以下幾點:
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。
我很欣賞答案......驗證了我的觀點。 –