WeakReference(弱引用)和SoftReference(弱引用)

如果你想写一个 Java 程序,观察某对象什么时候会被垃圾收集的执行绪清除,你必须要用一个 reference 记住此对象,以便随时观察,但是却因此造成此对象的 reference 数目一直无法为零, 使得对象无法被清除。

 java.lang.ref.WeakReference

  不过,现在有了 Weak Reference 之后,这就可以迎刃而解了。如果你希望能随时取得某对象的信息,但又不想影响此对象的垃圾收集,那么你应该用 Weak Reference 来记住此对象,而不是用一般的 reference。

 Soft Reference 虽然和 Weak Reference 很类似,但是用途却不同。 被 Soft Reference 指到的对象,即使没有任何 Direct Reference,也不会被清除。一直要到 JVM 内存不足时且 没有 Direct Reference 时才会清除,SoftReference 是用来设计 object-cache 之用的。如此一来 SoftReference 不但可以把对象 cache 起来,也不会造成内存不足的错误 (OutOfMemoryError)。我觉得 Soft Reference 也适合拿来实作 pooling 的技巧。


import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;
import java.util.HashMap;

public class Test {

	/**
	 * @param args
	 */
	public static void main(String[] args) {

		HashMap ref = new HashMap();
		ref.put("StrongRef", new Finalize("obj"));
		ref.put("SoftRef", new SoftReference(new Finalize("soft")));
		ref.put("WeakRef", new WeakReference(new Finalize("weak")));

		try {
			HashMap map = new HashMap();
			for (int i = 0; i < Integer.MAX_VALUE; i++) {
				map.put("KEY" + i, "VALUE" + i);
			}
		} catch (OutOfMemoryError oom) {
			System.out.println(" obj oom--->" + ref.get("StrongRef"));
			System.out.println("soft oom--->"
					+ ((SoftReference) ref.get("SoftRef")).get());
			System.out.println("weak oom--->"
					+ ((WeakReference) ref.get("WeakRef")).get());
		}
	}

	static class Finalize {

		private String name;

		public Finalize(String name) {
			super();
			this.name = name;
		}

		protected void finalize() throws Throwable {
			Runtime runtime = Runtime.getRuntime();
			System.out.println(this.name + " finalize"+".free:"+runtime.freeMemory()/1024+" total:"+runtime.totalMemory()/1024);
		}

		public String toString() {
			return this.name;
		}
	}

}


输出:
weak finalize.free:5332 total:7872
soft finalize.free:328 total:7872
obj oom--->obj
soft oom--->null
weak oom--->null

猜你喜欢

转载自san-yun.iteye.com/blog/1569380