同样的我们测试一下:
@Test
public void weakReference() {
Object referent = new Object();
WeakReference<Object> weakRerference = new WeakReference<Object>(referent);
assertSame(referent, weakRerference.get());//referent '强可及'
System.gc();
assertNotNull(weakRerference.get());
assertNotNull(referent);//referent '强可及' 不会被回收
referent = null;//取消强引用,referent '弱可及'
System.gc();
assertNull(weakRerference.get()); //'弱可及'将被回收,此时内存充裕
referent = null;
System.gc();
assertNull(weakRerference.get()); //`不可及`
}
  '强可及','软可及' ,'弱可及' ,'不可及'这些引用状态简直看的人一脸懵逼呀。先不要慌,我们来看看oracle是怎么定义这些状态的:
  Reachability
  Going from strongest to weakest, the different levels of reachability reflect the life cycle of an object. They are operationally defined as follows:
  · An object is strongly reachable if it can be reached by some thread without traversing any reference objects. A newly-created object is strongly reachable by the thread that created it.
  · An object is softly reachable if it is not strongly reachable but can be reached by traversing a soft reference.
  · An object is weakly reachable if it is neither strongly nor softly reachable but can be reached by traversing a weak reference. When the weak references to a weakly-reachable object are cleared, the object becomes eligible for finalization.
  · An object is phantom reachable if it is neither strongly, softly, nor weakly reachable, it has been finalized, and some phantom reference refers to it.
  Finally, an object is unreachable, and therefore eligible for reclamation, when it is not reachable in any of the above ways.
  Since:
  1.2
  自然而然的Since 1.2 ,看下文档再对比下Test,现在应该明朗多了吧。
  PhantomReference:
  Phantom reference objects, which are enqueued after the collector determines that their referents may otherwise be reclaimed. Phantom references are most often used for scheduling pre-mortem cleanup actions in a more flexible way than is possible with the Java finalization mechanism.If the garbage collector determines at a certain point in time that the referent of a phantom reference is phantom reachable, then at that time or at some later time it will enqueue the reference.
  In order to ensure that a reclaimable object remains so, the referent of a phantom reference may not be retrieved: The get method of a phantom reference always returns null.
  Unlike soft and weak references, phantom references are not automatically cleared by the garbage collector as they are enqueued. An object that is reachable via phantom references will remain so until all such references are cleared or themselves become unreachable.
  · 一个对象仅如果持有虚引用,那么它和没有任何引用一样,在任何时候都可能被垃圾回收器回收。
  · 虚引用主要用来跟踪对象被垃圾回收器回收的活动。