System.gc();
System.out.println("Sleeping");
Thread.sleep(5000);
}
publicstaticvoid main(String args[]) throws InterruptedException {
System.out.println("Creating weak references");
// This is now a weak reference.
// The object will be collected only if no strong references.
Referred strong = new Referred();
Map
metadata.put(strong, "WeakHashMap's make my world go around");
// Attempt to claim a suggested reference.
ClassWeakHashMap.collect();
System.out.println("Still has metadata entry " + (metadata.size() == 1));
System.out.println("Removing reference");
// The object may be collected.
strong = null;
ClassWeakHashMap.collect();
System.out.println("Still has metadata entry " + (metadata.size() == 1));
System.out.println("Done");
}
}
Output:
Creating weak references
Suggesting collection
Sleeping
Still has metadata entry true
Removing reference
Suggesting collection
Sleeping
Good bye cruel world
Still has metadata entry false
Done