package Tools;

import java.util.*;

/**
 * A tool to organize data that should be stored per-thread.
 * Cannot inherit bindings when creating subthreads.
 *
 * @todo I think Java has finally added support for this sort of
 * thing in JDK 1.2 --- look into it and deprecate this class.
 */
public class PerThread {
	Map threadToObjectMap;
	Object defaultObject;

	public PerThread(Object defaultObject) {
		this.defaultObject = defaultObject;
		threadToObjectMap = new HashMap();
	}

	public PerThread() {
		this(null);
	}

	/**
	 * Establish which object should be returned on a get() call if no
	 * object is yet defined for the calling thread
	 */
	public void setDefault(Object defaultObject) {
		this.defaultObject = defaultObject;
	}

	/**
	 * Establish the object to associate with the current thread.
	 */
	public void set(Object object) {
		threadToObjectMap.put(Thread.currentThread(), object);
		// System.err.println("set "+Thread.currentThread().hashCode()+" -> "+object);
	}

	/**
	 * Return the object associated with this thread, or the default
	 * object if there is none.
	 */
	public Object get() {
		Object o = threadToObjectMap.get(Thread.currentThread());
		// System.err.println("get "+Thread.currentThread().hashCode()+" -> "+o);
		if (o==null) {
			o = defaultObject;
		}
		return o;
	}
}
