package org.jcon.util.lock;

import java.util.Enumeration;
import java.util.Hashtable;

/**
 * Provides a set of named locked objects for exclusive
 * use by the client, typically for a transaction.
 * <p>
 * Note that proxy objects may be used to provide concurrency
 * protection for their counterparts. For example database
 * tables may have their String names as proxies. In cases
 * like this the LockSet holder doesn't need to call
 * LockSet.get() at all since the object is an irrelevant
 * dummy object and the key is the name.
 *
 * @author Jack Harich
 */
public class LockSet implements java.io.Serializable {

//---------- Private Fields ------------------------------
// Key = Object key, Object = Resource
private Hashtable resources = new Hashtable();

private String id;

//---------- Initialization ------------------------------
public LockSet(String id) {
    this.id = id;
}
//---------- Properties ----------------------------------
public String getID() {
    return id;
}
//---------- Public Methods ------------------------------
/**
 * Returns the object for the key or null if not found.
 */
public Object get(Object key) {
    Resource resource = (Resource)resources.get(key);
    if (resource == null) {
        return null;
    } else {
        return resource.getObject();
    }
}
/**
 * Returns true if the LockSet contains the key, false if not.
 */
public boolean containsKey(Object key) {
    return resources.containsKey(key);
}
/**
 * Returns an Enumeration of the object keys. Since the
 * keys are immutable after the LockSet is created by
 * LockPool, the Enumeration is threadsafe.
 */
public Enumeration getKeys() {
    return resources.keys();
}
//---------- Package Methods -----------------------------
void add(Resource resource) {
    resources.put(resource.getKey(), resource);
}
// Order irrelevant
void unlockAll() {
    Enumeration enum = resources.elements();
    while (enum.hasMoreElements()) {
        Resource resource = (Resource)enum.nextElement();
        print(".unlockAll() ------ Unlocking " + resource.getKey());
        resource.setLocked(false);
    }
}
//---------- Private Methods -----------------------------
//--- Std
private static void print(String text) {
    if (LockPool.DEBUGGING) System.out.println("LockSet" + text);
}

} // End class
