FileDocCategorySizeDatePackage
UsingReferences.javaAPI DocExample2410Sun Dec 14 22:47:30 GMT 2003oreilly.hcj.references

UsingReferences

public class UsingReferences extends Object
Demonstrates usign reference queues. (Mostly used for syntax checking examples)
author
Robert Simmons jr. (kraythe)
version
$Revision: 1.4 $

Fields Summary
Set
whs
Holds a weak hash set.
String
a
The demo object: Joe.
String
b
The demo object: Fred.
String
c
The demo object: John.
Constructors Summary
Methods Summary
public voiddangerous()
A dangerous method with weak references. Note the failure to grab a strong reference immediately.

	
		whs.add(a);
		whs.add(b);
		whs.add(c);
	
		Reference temp = null;
		Iterator iter = whs.iterator();
		while (iter.hasNext()) {
			temp = (Reference)iter.next();
			// .. do some code. 
			System.out.println(((String)temp.get()).length());
		}
	
public voidsafe()
A safe method with weak references. User grabs a strong reference to the referent immediately.

		String str = null;
		Iterator iter = whs.iterator();
		while (iter.hasNext()) {
			str = (String)((Reference)iter.next()).get();
			if (str != null) {
				// .. do some code. 
				System.out.println(str.length());
			}
		}
	
public voidsomeMethod()
Demonstration of reference queues.

		Object obj = new Object();
		WeakReference ref = new WeakReference(obj);

		ReferenceQueue clearedObjects = new ReferenceQueue();
		SoftReference ref2 = new SoftReference(obj, clearedObjects);

		// just used to supress eclipse warnings.
		ref.isEnqueued();
		ref2.isEnqueued();