java WeekReference ReferenceQueue测试

构建WeekReference(referent, referenceQueue)对象时,代表referent指向的对象要被回收时,当 WeekReference对象放到referenceQueue队列里,WeekReference对象的引用要一直保持,不能被回收。如下例所示,如果没有最后的打印wrapper操作,wrapper也会被回收,则从referenceQueue队列里会一直取不到数据。

import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;

class WeekReferenceWrapper extends WeakReference<RefObject> {
	private String name = "";

	public WeekReferenceWrapper(RefObject referent, ReferenceQueue referenceQueue, String name) {
		super(referent, referenceQueue);
		this.name = name;
	}

	protected void finalize() throws Throwable {
		System.out.println("finalize WeekReferenceWrapper: " + name);
	}
}

class RefObject {
	private String name;

	public RefObject(String name) {
		this.name = name;
	}

	protected void finalize() throws Throwable {
		System.out.println("finalize RefObject: " + name);
	}
}

public class WeekReferenceTest {
	public static void main(String[] args) throws IllegalArgumentException, InterruptedException {
		ReferenceQueue<WeekReferenceWrapper> referenceQueue = new ReferenceQueue<WeekReferenceWrapper>();
		WeekReferenceWrapper wrapper = new WeekReferenceWrapper(new RefObject("t_1"), referenceQueue, "WeekReferenceWrapper_1");
		for (int i = 0; i < 10; i++) {
			Reference<? extends WeekReferenceWrapper> r = referenceQueue.remove(100);
			if (r != null) {
				System.out.println("r:" + r);
			}
			System.gc();
		}

		System.out.println("Program end, wrapper:" + wrapper);
	}

}
相关文章

相关标签/搜索
每日一句
    每一个你不满意的现在,都有一个你没有努力的曾经。