弱引用 WeakReference: 并不能使对象豁免垃圾收集,仅仅是提供一种访问在弱引用状态下对象的途径。这就可以用来构建一种没有特定约束的关系,如果试图获取时对象还在,就使用它,否则重现实例化。它同样是很多缓存实现的选择。这个类对象的引用,一般主要是在 major collection 的时候回收,所以它可能在 minor collection 后仍然存在。
**虚引用 PhantomReference: **The object is the referent of a PhantomReference, and it has already been selected for collection and its finalizer (if any) has run. The term “reachable” is really a misnomer in this case, as there’s no way for you to access the actual object. 不可达, 不影响对象的生命周期, 通过虚引用的 get() 方法永远返回 null.
A reference object is a layer of indirection between your program code and some other object, called a referent. Each reference object is constructed around its referent, and the referent cannot be changed.
Entry<K,V> prev = table[i];// 取得 table [i] 处链表的第一个元素 Entry<K,V> p = prev; while (p != null) {// 链表是否为空或者是否是链表的最后一个元素 Entry<K,V> next = p.next; if (p == e) { // 找到了要被清理的元素 if (prev == e)// prev 不一定和 p 相同 table[i] = next; // 用下一个元素对 e 元素替换 else prev.next = next; // 修复链接 // Must not null out e.next; // stale entries may be in use by a HashIterator e.value = null; // Help GC size--; break; } prev = p; // 没找到要被清理的元素,交换指针,移动位置,继续比对 p = next; } } } }
/** * Creates a new weak reference that refers to the given object and is * registered with the given queue. * * @param referent object the new weak reference will refer to * @param q the queue with which the reference is to be registered, * or <tt>null</tt> if registration is not required * * 监听器效果, 如果引用的对象被回收(reference.get() == null),则将其加入该队列 */ publicWeakReference(T referent, ReferenceQueue<? super T> q) { super(referent, q); }
// 2. get 方法分析 public V get(Object key) { Objectk= maskNull(key); inth= hash(k); Entry<K,V>[] tab = getTable(); intindex= indexFor(h, tab.length); Entry<K,V> e = tab[index]; while (e != null) { if (e.hash == h && eq(k, e.get())) return e.value; e = e.next; } returnnull; }