Java 2 平台引入了 java.lang.ref包,其中包括的类可以让您引用对象,而不将它们留在内存中。这些类还提供了与垃圾收集器(garbagecollector)之间有限的交互。
WeakReference 类
WeakReference weakref = new WeakReference(ref);
SoftReference 类
Object obj = new char[1000000];
soft reference:
SoftReference ref = new SoftReference(obj);
if (ref.get() == null)// (referent has been cleared)
else// (referent has not been cleared)
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;
}
}
}