Classes in this File | Line Coverage | Branch Coverage | Complexity | ||||
Lock |
|
| 3.0;3 |
1 | /* | |
2 | * Copyright (C) The Apache Software Foundation. All rights reserved. | |
3 | * | |
4 | * This software is published under the terms of the Apache Software License | |
5 | * version 1.1, a copy of which has been included with this distribution in | |
6 | * the LICENSE file. | |
7 | * | |
8 | * $Id: Lock.java 155459 2005-02-26 13:24:44Z dirkv $ | |
9 | */ | |
10 | package org.apache.commons.messenger; | |
11 | ||
12 | import javax.jms.JMSException; | |
13 | ||
14 | /** <p><code>Lock</code> is a simple lock. | |
15 | * | |
16 | * @author <a href="mailto:jstrachan@apache.org">James Strachan</a> | |
17 | * @version $Revision: 155459 $ | |
18 | */ | |
19 | 0 | public class Lock { |
20 | ||
21 | private Thread owner; | |
22 | private int count; | |
23 | ||
24 | /** | |
25 | * Acquires the lock, blocking until the lock can be acquired | |
26 | * @throws InterruptedException | |
27 | */ | |
28 | public void acquire() { | |
29 | 0 | Thread caller = Thread.currentThread(); |
30 | 0 | synchronized (this) { |
31 | 0 | if (caller == owner) { |
32 | 0 | count++; |
33 | } | |
34 | else { | |
35 | 0 | while (owner != null) { |
36 | try { | |
37 | 0 | wait(); |
38 | } | |
39 | 0 | catch (InterruptedException ex) { |
40 | // ignore | |
41 | 0 | } |
42 | } | |
43 | 0 | owner = caller; |
44 | 0 | count = 1; |
45 | ||
46 | // System.out.println("Lock: " + this + " acquired by + "+ caller ); | |
47 | // new Exception().printStackTrace(); | |
48 | } | |
49 | 0 | } |
50 | 0 | } |
51 | ||
52 | /** | |
53 | * Release the lock. | |
54 | **/ | |
55 | public synchronized void release() throws JMSException { | |
56 | 0 | if (Thread.currentThread() != owner) { |
57 | 0 | throw new JMSException("Cannot release lock - not the current owner"); |
58 | } | |
59 | else { | |
60 | 0 | if (--count == 0) { |
61 | // System.out.println("Lock: " + this + " released by + "+ owner ); | |
62 | // new Exception().printStackTrace(); | |
63 | ||
64 | 0 | owner = null; |
65 | ||
66 | 0 | notify(); |
67 | } | |
68 | } | |
69 | 0 | } |
70 | ||
71 | /** | |
72 | * @return | |
73 | */ | |
74 | public synchronized boolean hasLock() { | |
75 | 0 | return Thread.currentThread() == owner; |
76 | } | |
77 | } |