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

UsingReferences.java

/*
 *     file: UsingReferences.java
 *  package: oreilly.hcj.references
 *
 * This software is granted under the terms of the Common Public License,
 * CPL, which may be found at the following URL:
 * http://www-124.ibm.com/developerworks/oss/CPLv1.0.htm
 *
 * Copyright(c) 2003-2005 by the authors indicated in the @author tags.
 * All Rights are Reserved by the various authors.
 *
########## DO NOT EDIT ABOVE THIS LINE ########## */

package oreilly.hcj.references;

import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;
import java.util.Iterator;
import java.util.Set;

/**  
 * Demonstrates usign reference queues. (Mostly used for syntax checking examples)
 *
 * @author <a href=mailto:kraythe@arcor.de>Robert Simmons jr. (kraythe)</a>
 * @version $Revision: 1.4 $
 */
public class UsingReferences {
	/** Holds a weak hash set. */
	Set whs = new WeakHashSet();

	/** The demo object: Joe. */
	String a = new String("joe");

	/** The demo object: Fred. */
	String b = new String("fred");

	/** The demo object: John. */
	String c = new String("john");
	{
		whs.add(a);
		whs.add(b);
		whs.add(c);
	}

	/** 
	 * A dangerous method with weak references.  Note the failure to grab a strong
	 * reference immediately.
	 */
	public void dangerous() {
		Reference temp = null;
		Iterator iter = whs.iterator();
		while (iter.hasNext()) {
			temp = (Reference)iter.next();
			// .. do some code. 
			System.out.println(((String)temp.get()).length());
		}
	}

	/** 
	 * A safe method with weak references.  User grabs a strong reference to the referent
	 * immediately.
	 */
	public void safe() {
		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());
			}
		}
	}

	/** 
	 * Demonstration of reference queues.
	 */
	public void someMethod() {
		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();
	}
}

/* ########## End of File ########## */