Java by API/java.lang.ref/SoftReference — различия между версиями

Материал из Java эксперт
Перейти к: навигация, поиск
м (1 версия)
 
(нет различий)

Текущая версия на 14:39, 31 мая 2010

new SoftReference(Object object, ReferenceQueue r)

  
import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.SoftReference;
import java.util.HashMap;
public class Main {
  public static void main(String[] args) {
    ReferenceQueue referenceQueue = new ReferenceQueue();
    Object object = new Object() {
      public String toString() {
        return "Referenced Object";
      }
    };
    Object data = new Object() {
      public String toString() {
        return "Data";
      }
    };
    HashMap map = new HashMap();
    Reference reference = new SoftReference(object, referenceQueue);
    map.put(reference, data);
    System.out.println(reference.get());
    System.out.println(map.get(reference));
    System.out.println(reference.isEnqueued());
    System.gc();
    System.out.println(reference.get());
    System.out.println(map.get(reference));
    System.out.println(reference.isEnqueued());
    object = null;
    data = null;
    System.gc();
    System.out.println(reference.get());
    System.out.println(map.get(reference));
    System.out.println(reference.isEnqueued());
  }
}





new SoftReference(String referent)

  
import java.lang.ref.SoftReference;
public class Main {
  public static void main(String[] argv) throws Exception {
    SoftReference<String> sr = new SoftReference<String>("object");
    Object o = sr.get();
    if (o != null) {
      System.out.println(o);
    } else {
      System.out.println("collected or has been reclaimed");
    }
  }
}





SoftReference: get()

  
import java.lang.ref.SoftReference;
public class Main {
  public static void main(String[] argv) throws Exception {
    SoftReference<String> sr = new SoftReference<String>("object");
    Object o = sr.get();
    if (o != null) {
      System.out.println(o);
    } else {
      System.out.println("collected or has been reclaimed");
    }
  }
}