Java Object References in JVM -- Phantom References (二)

2014-11-24 10:43:47 · 作者: · 浏览: 1
tem.out.println("Suggesting collection");

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 = new WeakHashMap();

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