new WeakReference(Object referent)
import java.lang.ref.WeakReference;
import java.util.Iterator;
import java.util.Map;
import java.util.WeakHashMap;
public class Main {
public static void main(String[] argv) throws Exception {
Object keyObject = "";
Object valueObject = "";
Map<Object, Object> weakMap = new WeakHashMap<Object, Object>();
weakMap.put(keyObject, valueObject);
WeakReference weakValue = new WeakReference<Object>(valueObject);
weakMap.put(keyObject, weakValue);
Iterator it = weakMap.keySet().iterator();
while (it.hasNext()) {
Object key = it.next();
weakValue = (WeakReference) weakMap.get(key);
if (weakValue == null) {
System.out.println("Value has been garbage-collected");
} else {
System.out.println("Get value");
valueObject = weakValue.get();
}
}
}
}
Related examples in the same category