001 /*
002 * Copyright (C) The Apache Software Foundation. All rights reserved.
003 *
004 * This software is published under the terms of the Apache Software License
005 * version 1.1, a copy of which has been included with this distribution in
006 * the LICENSE file.
007 *
008 * $Id: Lock.java 155459 2005-02-26 13:24:44Z dirkv $
009 */
010 package org.apache.commons.messenger;
011
012 import javax.jms.JMSException;
013
014 /** <p><code>Lock</code> is a simple lock.
015 *
016 * @author <a href="mailto:jstrachan@apache.org">James Strachan</a>
017 * @version $Revision: 155459 $
018 */
019 public class Lock {
020
021 private Thread owner;
022 private int count;
023
024 /**
025 * Acquires the lock, blocking until the lock can be acquired
026 * @throws InterruptedException
027 */
028 public void acquire() {
029 Thread caller = Thread.currentThread();
030 synchronized (this) {
031 if (caller == owner) {
032 count++;
033 }
034 else {
035 while (owner != null) {
036 try {
037 wait();
038 }
039 catch (InterruptedException ex) {
040 // ignore
041 }
042 }
043 owner = caller;
044 count = 1;
045
046 // System.out.println("Lock: " + this + " acquired by + "+ caller );
047 // new Exception().printStackTrace();
048 }
049 }
050 }
051
052 /**
053 * Release the lock.
054 **/
055 public synchronized void release() throws JMSException {
056 if (Thread.currentThread() != owner) {
057 throw new JMSException("Cannot release lock - not the current owner");
058 }
059 else {
060 if (--count == 0) {
061 // System.out.println("Lock: " + this + " released by + "+ owner );
062 // new Exception().printStackTrace();
063
064 owner = null;
065
066 notify();
067 }
068 }
069 }
070
071 /**
072 * @return
073 */
074 public synchronized boolean hasLock() {
075 return Thread.currentThread() == owner;
076 }
077 }