原则: weak reference与垃圾收集相关。通常,具有一个或多个对象的对象。reference将不符合垃圾收集的条件。
上述原则不适用于下列情况:weak reference..如果一个对象与其他对象只有弱引用,那么它就可以进行垃圾回收了。
让我们看看下面的例子:我们有一个Map使用键是引用对象的对象。import java.util.HashMap; public class Test {
public static void main(String args[]) {
HashMap aMap = new
HashMap();
Employee emp = new Employee("Vinoth");
EmployeeVal val = new EmployeeVal("Programmer");
aMap.put(emp, val);
emp = null;
System.gc();
System.out.println("Size of Map" + aMap.size());
}}
现在,在程序的执行过程中emp = null..这个Map在这里握着钥匙是没有意义的null..在上述情况下,对象不是垃圾收集。
WeakHashMap
WeakHashMap是条目(key-to-value mappings)不再可能从Map.
让我展示上面的例子WeakHashMapimport java.util.WeakHashMap;public class Test {
public static void main(String args[]) {
WeakHashMap aMap =
new WeakHashMap();
Employee emp = new Employee("Vinoth");
EmployeeVal val = new EmployeeVal("Programmer");
aMap.put(emp, val);
emp = null;
System.gc();
int count = 0;
while (0 != aMap.size()) {
++count;
System.gc();
}
System.out.println("Took " + count + " calls to System.gc() to result in weakHashMap size of : "
+ aMap.size());
}}
产出:拿20 calls to System.gc()导致aMap size编号:0。
WeakHashMap只有对键的弱引用,而不像其他引用那样具有强引用。Map上课。有些情况下,当值或键被强烈引用时,您必须小心,尽管您已经使用了WeakHashMap..通过将对象包装在WeakReference.import java.lang.ref.WeakReference;import java.util.HashMap;public class Test {
public static void main(String args[]) {
HashMap map =
new HashMap();
WeakReference> aMap =
new WeakReference>(
map);
map = null;
while (null != aMap.get()) {
aMap.get().put(new Employee("Vinoth"),
new EmployeeVal("Programmer"));
System.out.println("Size of aMap " + aMap.get().size());
System.gc();
}
System.out.println("Its garbage collected");
}}
软引用。
Soft Reference是稍强一点的弱引用。软引用允许垃圾收集,但只有在没有其他选项的情况下,才会请求垃圾收集器清除它。
垃圾收集器不像对弱可达对象那样积极地收集软可达对象,而是只在真正“需要”内存时收集软可达对象。软引用是对垃圾收集器说的一种方式,“只要内存不太紧,我想把这个对象留在身边。但是如果内存真的很紧,就去收集它,我会处理的。”垃圾收集器需要清除所有软引用,然后才能抛出OutOfMemoryError.