I thought WeakReference refer object will be finalized after System.gc() called, but I'm wrong.
Here are two test cases, the only difference is WeakReference constructor, the first one new an object while the second one use a referer, and they have different performance, I don't konw why...
Weak reference objects, which do not prevent their referents from being made finalizable, finalized, and then reclaimed. Weak references are most often used to implement canonicalizing mappings.
Suppose that the garbage collector determines at a certain point in time that an object is weakly reachable. At that time it will atomically clear all weak references to that object and all weak references to any other weakly-reachable objects from which that object is reachable through a chain of strong and soft references. At the same time it will declare all of the formerly weakly-reachable objects to be finalizable. At the same time or at some later time it will enqueue those newly-cleared weak references that are registered with reference queues.
package com.zeng.javaReference;
import org.junit.Test;
import java.lang.ref.WeakReference;
/**
* @author zeng
* @version 1.0.0
* @date 2020-05-11
*/
public class WeakReferenceTest {
@Test
public void weakRefRemoved() {
WeakReference<Apple> weakReference = new WeakReference<>(new Apple("green-apple"));
System.gc();
if (weakReference.get() == null) {
System.out.println("GC remove weakReference!");
} else {
System.out.println("weakReference still alive");
}
}
@Test
public void weakRefNotRemoved() {
Apple apple = new Apple("green-apple");
WeakReference<Apple> weakReference = new WeakReference<>(apple);
System.gc();
if (weakReference.get() == null) {
System.out.println("GC remove weakReference!");
} else {
System.out.println("weakReference still alive");
}
}
public static class Apple {
private String name;
public Apple(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
protected void finalize() throws Throwable {
super.finalize();
System.out.println("Apple: " + name + " finalized。");
}
@Override
public String toString() {
return "Apple{" +
"name='" + name + '\'' +
'}' + ", hashCode:" + this.hashCode();
}
}
}