When I was learning about threadlocal, I was puzzled by its weak reference recycling mechanism, so I have the following test code:
public static void main(String[] args) {
Car car = new Car(22000, "sliver");
Entry entry = new Entry(car, new Object());
int i = 0;
while (true) {
if (entry.get() != null) {
i++;
System.out.println("Object is alive for " + i + " loops - " + entry);
} else {
// Object is alive for 61441 loops - Entry@490d6c15
// null,java.lang.Object@7d4793a8
// Object has been collected.
System.out.println(entry.get() + "," + entry.getValue());
System.out.println("Object has been collected.");
break;
}
}
}
class Car {
private double price;
private String colour;
public Car(double price, String colour) {
this.price = price;
this.colour = colour;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getColour() {
return colour;
}
public void setColour(String colour) {
this.colour = colour;
}
}
class Entry extends WeakReference<Car> {
Object value;
Entry(Car k, Object v) {
super(k);
value = v;
}
public Object getValue() {
return value;
}
}
In my computer, it will execute to the else branch
after 6W cycles
My question is:
Why entry.get()
is return null, there is also a strong reference in front: Car car = new Car(22000, "sliver");