What is the difference between using WeakReference and setting the strong ref type to null ?
Say for example in the following code the variable "test" is a strong ref to "testString". When I set the "test" to null. There is no longer a Strong ref and hence "testString" is now eligible for GC. So if I can simply set the object reference "test" to equal null what is the point of having a WeakReference Type ?
class CacheTest {
private String test = "testString";
public void evictCache(){
test = null; // there is no longer a Strong reference to "testString"
System.gc(); //suggestion to JVM to trigger GC
}
}
Why would i ever want to use WeakReference ?
class CacheTest {
private String test = "testString";
private WeakReference<String> cache = new WeakReference<String>(test);
public void evictCache(){
test = null; // there is no longer a Strong reference to "testString"
System.gc(); //suggestion to JVM to trigger GC
}
}