Android 弱引用

Android 弱引用
public class reference {
	private StringBuilder stringBuilder;

	public reference() {
		// TODO Auto-generated constructor stub
		stringBuilder = new StringBuilder("test");
	}

	public StringBuilder getRefence() {
		return stringBuilder;
	}
}
public class Reference_test {

	static reference ref;
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		ref = new reference();
	    WeakReference weakRef = new WeakReference(ref);  
	    
	    ref = null;
	    System.gc();
	    
	    reference ref2 = weakRef.get();
	    if (ref2 == null) {
	    	System.out.println("gc");
	    } else {
	    	System.out.println(ref2.toString());
	    }
	    
	}
	
}

输出结果为:gc;

这说明只要JVM进行垃圾回收,被弱引用关联的对象必定会被回收掉。不过要注意的是,这里所说的被弱引用关联的对象是指只有弱引用与之关联,如果存在强引用同时与之关联,则进行垃圾回收时也不会回收该对象



你可能感兴趣的:(android)