package jacorb.imr;

/**
 * This class provides shared or exclusive access to a ressource.
 * It preferes the exclusive access, i.e. if threads are waiting for 
 * exclusive access, shared locks can't be gained.
 *
 * @author Nicolas Noffke
 * 
 * $Log: RessourceLock.java,v $
 * Revision 1.5  1999/11/25 16:04:55  brose
 * cosmetics
 *
 * Revision 1.4  1999/11/09 10:59:27  brose
 * new GUI version
 *
 * Revision 1.2  1999/10/29 19:24:29  noffke
 * Cosmetics, now fully commented , adapted to new/altered methods from the
 * interface
 *
 *
 */

public class RessourceLock implements java.io.Serializable {
    private int m_shared;
    private int m_exclusive;
    private boolean m_exclusives_waiting = false;

    /**
     * The constructor.
     **/
    public RessourceLock() {
	m_shared = 0;
	m_exclusive = 0;
    }

    /**
     * This method tries to aquire a shared lock. It blocks
     * until the exclusive lock is released.
     **/
    public synchronized void gainSharedLock(){
	while(m_exclusive > 0 && m_exclusives_waiting){
	    try{
		wait();
	    }catch (java.lang.Exception _e){
		jacorb.util.Debug.output(2, _e);
	    }
	}
	m_shared++;
    }

    /**
     * Release the shared lock. Unblocks threads waiting for
     * access.
     **/
    public synchronized void releaseSharedLock(){
	if (--m_shared == 0)
	    notifyAll();
    }

    /**
     * This method tries to aquire an exclusive lock. It blocks until
     * all shared locks have been released.
     **/
    public synchronized void gainExclusiveLock(){
	while(m_shared > 0 || m_exclusive > 0){
	    try{
		m_exclusives_waiting = true;
		wait();
	    }catch (java.lang.Exception _e){
		jacorb.util.Debug.output(2, _e);
	    }
	}
	m_exclusive++;
	m_exclusives_waiting = false;
    }

    /**
     * Releases the exclusive lock. Unblocks all threads waiting
     * for access.
     **/
    public synchronized void releaseExclusiveLock(){
	if (--m_exclusive == 0)
	    notifyAll();
    }

} // RessourceLock


