package weakreference;
/**
* @author wison
*/
public 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;
}
public string tostring(){
return colour +"car costs $"+price;
}
}
package weakreference;
import java.lang.ref.weakreference;
/**
* @author wison
*/
public class testweakreference {
public static void main(string[] args) {
car car = new car(22000,"silver");
weakreference<car> weakcar = new weakreference<car>(car);
int i=0;
while(true){
if(weakcar.get()!=null){
i++;
system.out.println("object is alive for "+i+" loops - "+weakcar);
}else{
system.out.println("object has been collected.");
break;
}
}
}
}
在上例中, 程序运行一段时间后, 程序打印出"object has been collected." 说明, weak reference指向的对象的被回收了.
值得注意的一点 , 即使有 car 引用指向对象, 且 car 是一个strong reference, weak reference weakcar指向的对象仍然被回收了. 这是因为java的编译器在发现进入while循环之后, car 已经没有被使用了, 所以进行了优化(将其置空?). 当把testweakreference.java修改为:
package weakreference;
import java.lang.ref.weakreference;
/**
* @author wison
*/
public class testweakreference {
public static void main(string[] args) {
car car = new car(22000,"silver");
weakreference<car> weakcar = new weakreference<car>(car);
int i=0;
while(true){
system.out.println("here is the strong reference 'car' "+car);
if(weakcar.get()!=null){
i++;
system.out.println("object is alive for "+i+" loops - "+weakcar);
}else{
system.out.println("object has been collected.");
break;
}
}
}
}