001: /*
002: * Copyright 2001-2006 C:1 Financial Services GmbH
003: *
004: * This software is free software; you can redistribute it and/or
005: * modify it under the terms of the GNU Lesser General Public
006: * License Version 2.1, as published by the Free Software Foundation.
007: *
008: * This software is distributed in the hope that it will be useful,
009: * but WITHOUT ANY WARRANTY; without even the implied warranty of
010: * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
011: * Lesser General Public License for more details.
012: *
013: * You should have received a copy of the GNU Lesser General Public
014: * License along with this library; if not, write to the Free Software
015: * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA
016: */
017:
018: package de.finix.contelligent.util;
019:
020: import de.finix.contelligent.logging.LoggingService;
021:
022: public class RWLock {
023: final static org.apache.log4j.Logger log = LoggingService
024: .getLogger(RWLock.class);
025:
026: private int givenLocks;
027:
028: private int waitingWriters;
029:
030: private Object mutex;
031:
032: public RWLock() {
033: mutex = new Object();
034: givenLocks = 0;
035: waitingWriters = 0;
036: }
037:
038: public void getReadLock() {
039: synchronized (mutex) {
040: try {
041: while ((givenLocks == -1) || (waitingWriters != 0)) {
042: if (log.isDebugEnabled()) {
043: log.debug(Thread.currentThread().toString()
044: + "waiting for readlock");
045: }
046: mutex.wait();
047: }
048: } catch (java.lang.InterruptedException e) {
049: log.debug("interrupted", e);
050: }
051:
052: givenLocks++;
053:
054: if (log.isDebugEnabled()) {
055: log.debug(Thread.currentThread().toString()
056: + " got readlock, GivenLocks = " + givenLocks);
057: }
058: }
059: }
060:
061: public void getWriteLock() {
062: synchronized (mutex) {
063: waitingWriters++;
064: try {
065: while (givenLocks != 0) {
066: if (log.isDebugEnabled()) {
067: log.debug(Thread.currentThread().toString()
068: + "waiting for writelock");
069: }
070: mutex.wait();
071: }
072: } catch (java.lang.InterruptedException e) {
073: log.debug("interrupted", e);
074: }
075:
076: waitingWriters--;
077: givenLocks = -1;
078:
079: if (log.isDebugEnabled()) {
080: log.debug(Thread.currentThread().toString()
081: + " got writelock, GivenLocks = " + givenLocks);
082: }
083: }
084: }
085:
086: public void releaseLock() {
087:
088: synchronized (mutex) {
089: if (givenLocks == 0) {
090: return;
091: }
092: if (givenLocks == -1) {
093: givenLocks = 0;
094: } else {
095: givenLocks--;
096: }
097: if (log.isDebugEnabled()) {
098: log.debug(Thread.currentThread().toString()
099: + " released lock, GivenLocks = " + givenLocks);
100: }
101:
102: mutex.notifyAll();
103: }
104: }
105: }
|