java 引用类型 WeakReference SoftReference 分析

转:java WeakReference SoftReference and PhatomRefer

 

 1、WeakReference:在垃圾回收器线程扫描它所管辖的内存区域过程中,一旦发现有弱引用的对象,不管当前内 存空间足够与否,都会回收它的内存

2、SoftReference:如果内存空间足够,垃圾回收器就不会回收它,如果内存空间不足了,就会回收这些对象的内存。 只要垃圾回收器没有回收它,该对象就可以被程序使用。软引用可用来实现内存敏感的高速缓存

3、区别:具有WeakReference的 对象拥有更短暂的生命周期。或者说SoftReference比WeakReference对回收它所指的对象不敏感。一个WeakReference对 象会在下一轮的垃圾回收中被清理,而SoftReference对象则会保存一段时间。SoftReferences并不会主动要求与 WeakReference有什么不同,但是实际上SoftReference对象一般在内存充裕时一般不会被移除,这就是说对于创建缓冲区它们是不错的 选择。它兼有了StrongReference和WeakReference的好处,既能停留在内存中,又能在内存不足是去处理,这一切都是自动的

4、SoftReference的使用:

   Object obj = new char[1000000];
SoftReference ref = new SoftReference(obj);
Obj是这个soft reference的引用。在以后你用以下的方式检测这个引用:
if (ref.get() == null)// (referent has been cleared)
else// (referent has not been cleared)\

 

注意:软引用可以和一个引用队列(ReferenceQueue)联合使用,如果软引用所引用的对象被垃圾回收,Java虚拟机就会把这个软引用加入到与之关联的引用队列中。

import java.lang.ref.*; 
 
public class References { 
  public static void main(String[] args) { 
    Object weakObj, phantomObj; 
    Reference ref; 
    WeakReference weakRef; 
    PhantomReference phantomRef; 
    ReferenceQueue weakQueue, phantomQueue; 
 
    weakObj    = new String("Weak Reference"); 
    phantomObj = new String("Phantom Reference"); 
    weakQueue    = new ReferenceQueue(); 
    phantomQueue = new ReferenceQueue(); 
    weakRef    = new WeakReference(weakObj, weakQueue); 
    phantomRef = new PhantomReference(phantomObj, phantomQueue); 
 
    // Print referents to prove they exist.  Phantom referents 
    // are inaccessible so we should see a null value. 
    System.out.println("Weak Reference: " + weakRef.get()); 
    System.out.println("Phantom Reference: " + phantomRef.get()); 
 
    // Clear all strong references 
    weakObj    = null; 
    phantomObj = null; 
 
    // Invoke garbage collector in hopes that references 
    // will be queued 
    System.gc(); 
 
    // See if the garbage collector has queued the references 
    System.out.println("Weak Queued: " + weakRef.isEnqueued()); 
    // Try to finalize the phantom references if not already 
    if(!phantomRef.isEnqueued()) { 
      System.out.println("Requestion finalization."); 
      System.runFinalization(); 
    } 
    System.out.println("Phantom Queued: " + phantomRef.isEnqueued()); 
 
    // Wait until the weak reference is on the queue and remove it 
    try { 
      ref = weakQueue.remove(); 
      // The referent should be null 
      System.out.println("Weak Reference: " + ref.get()); 
      // Wait until the phantom reference is on the queue and remove it 
      ref = phantomQueue.remove(); 
      System.out.println("Phantom Reference: " + ref.get()); 
      // We have to clear the phantom referent even though 
      // get() returns null 
      ref.clear(); 
    } catch(InterruptedException e) { 
      e.printStackTrace(); 
      return; 
    } 
  } 
}   



 

你可能感兴趣的:(java,String,object,null,import,reference)