001: package org.jacorb.imr;
002:
003: /*
004: * JacORB - a free Java ORB
005: *
006: * Copyright (C) 1999-2004 Gerald Brose
007: *
008: * This library is free software; you can redistribute it and/or
009: * modify it under the terms of the GNU Library General Public
010: * License as published by the Free Software Foundation; either
011: * version 2 of the License, or (at your option) any later version.
012: *
013: * This library is distributed in the hope that it will be useful,
014: * but WITHOUT ANY WARRANTY; without even the implied warranty of
015: * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
016: * Library General Public License for more details.
017: *
018: * You should have received a copy of the GNU Library General Public
019: * License along with this library; if not, write to the Free
020: * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
021: *
022: */
023:
024: /**
025: * This class provides shared or exclusive access to a ressource.
026: * It preferes the exclusive access, i.e. if threads are waiting for
027: * exclusive access, shared locks can't be gained.
028: *
029: * @author Nicolas Noffke
030: *
031: * $Id: ResourceLock.java,v 1.3 2004/05/06 12:39:59 nicolas Exp $
032: *
033: */
034:
035: public class ResourceLock implements java.io.Serializable {
036: private int shared;
037: private int exclusive;
038: private boolean exclusives_waiting = false;
039:
040: /**
041: * The constructor.
042: */
043:
044: public ResourceLock() {
045: shared = 0;
046: exclusive = 0;
047: }
048:
049: /**
050: * This method tries to aquire a shared lock. It blocks
051: * until the exclusive lock is released.
052: */
053:
054: public synchronized void gainSharedLock() {
055: while (exclusive > 0 && exclusives_waiting) {
056: try {
057: wait();
058: } catch (java.lang.Exception _e) {
059: }
060: }
061: shared++;
062: }
063:
064: /**
065: * Release the shared lock. Unblocks threads waiting for
066: * access.
067: */
068:
069: public synchronized void releaseSharedLock() {
070: if (--shared == 0)
071: notifyAll();
072: }
073:
074: /**
075: * This method tries to aquire an exclusive lock. It blocks until
076: * all shared locks have been released.
077: */
078:
079: public synchronized void gainExclusiveLock() {
080: while (shared > 0 || exclusive > 0) {
081: try {
082: exclusives_waiting = true;
083: wait();
084: } catch (java.lang.Exception _e) {
085: }
086: }
087: exclusive++;
088: exclusives_waiting = false;
089: }
090:
091: /**
092: * Releases the exclusive lock. Unblocks all threads waiting
093: * for access.
094: */
095:
096: public synchronized void releaseExclusiveLock() {
097: if (--exclusive == 0)
098: notifyAll();
099: }
100:
101: } // ResourceLock
|