KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sun > enterprise > util > sync > Lock


1 /*
2  * The contents of this file are subject to the terms
3  * of the Common Development and Distribution License
4  * (the License). You may not use this file except in
5  * compliance with the License.
6  *
7  * You can obtain a copy of the license at
8  * https://glassfish.dev.java.net/public/CDDLv1.0.html or
9  * glassfish/bootstrap/legal/CDDLv1.0.txt.
10  * See the License for the specific language governing
11  * permissions and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL
14  * Header Notice in each file and include the License file
15  * at glassfish/bootstrap/legal/CDDLv1.0.txt.
16  * If applicable, add the following below the CDDL Header,
17  * with the fields enclosed by brackets [] replaced by
18  * you own identifying information:
19  * "Portions Copyrighted [year] [name of copyright owner]"
20  *
21  * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
22  */

23
24 //NOTE: Tabs are used instead of spaces for indentation.
25
// Make sure that your editor does not replace tabs with spaces.
26
// Set the tab length using your favourite editor to your
27
// visual preference.
28

29 /*
30  * Filename: Lock.java
31  *
32  * Copyright 2000-2001 by iPlanet/Sun Microsystems, Inc.,
33  * 901 San Antonio Road, Palo Alto, California, 94303, U.S.A.
34  * All rights reserved.
35  *
36  * This software is the confidential and proprietary information
37  * of iPlanet/Sun Microsystems, Inc. ("Confidential Information").
38  * You shall not disclose such Confidential Information and shall
39  * use it only in accordance with the terms of the license
40  * agreement you entered into with iPlanet/Sun Microsystems.
41  */

42  
43 /**
44  * <BR> <I>$Source: /cvs/glassfish/appserv-commons/src/java/com/sun/enterprise/util/sync/Lock.java,v $</I>
45  * @author $Author: tcfujii $
46  * @version $Revision: 1.3 $ $Date: 2005/12/25 04:12:31 $
47  */

48  
49
50 package com.sun.enterprise.util.sync;
51
52 import java.lang.Thread JavaDoc;
53 import java.lang.InterruptedException JavaDoc;
54 import java.lang.IllegalMonitorStateException JavaDoc;
55
56 import com.sun.enterprise.util.pool.TimedoutException;
57
58 /**
59  * A <i>Lock</i> is a concurrency control class to support mutual exclusion. Some of
60  * the additional functionality that is provided by this class w.r.t. synchronized
61  * are :
62  * <ul>
63  * <li> time out based lock acquiring semantics
64  * <li> supports try lock semantics (isLocked())
65  * <li> lock ownership can be determined (getOwner())
66  * </ul>
67  * The usage pattern is the standard acquire/release protocol.
68  * <p>
69  * The usage of Lock can be see as under:
70  * <p><hr><blockquote><pre>
71  * public class MyHashTable {
72  * private Lock lock = new Lock();
73  * .....
74  * .....
75  * public Object get(Key k) {
76  * try {
77  * lock.acquire()
78  * ....perform search to get the Object ...
79  * } finally {
80  * lock.release()
81  * }
82  * }
83  *
84  * public Object set(Key k, Object o) {
85  * try {
86  * lock.acquire()
87  * ....perform operation to insert object ...
88  * } finally {
89  * lock.release()
90  * }
91  * }
92  * }
93  * </pre></blockquote><hr>
94  * <p>
95  * This version of Lock also supports time out semantics when trying to acquire a
96  * lock. If the lock is not acquired in the timeout parameter specified, a
97  * TimedOutException is thrown. This would be extremely useful in avoiding deadlock
98  * situations especially in I/O related multi-threaded access patterns.
99  * <p>
100  * This implementation of Lock is reentrant i.e. if the a thread that has a Lock
101  * and tries to acquire the same lock, it would be given the lock
102  * <p>
103  * @author Dhiru Pandey 8/1/2000
104  */

105
106 public class Lock {
107
108     private Thread JavaDoc owner = null; // Current owner of the Lock
109
private int lockCount = 0; // number of times the lock is acquired by the owner
110

111 /**
112  * This method tries to acquire the lock and waits forever till the lock becomes
113  * available. If the lock is available, the invoking
114  * thread proceeds else it ends up waiting till the lock becomes available. If the
115  * invoking thread has already acquired this lock and tries to acquire it again the
116  * lock object allows it to acquire it again.
117  * <p>
118  * @throws InterruptedException thrown if the calling thread is interrupted during
119  * the execution of acquire()
120  */

121     public synchronized void acquireLock() throws InterruptedException JavaDoc {
122         while(! tryGetLock())
123             wait();
124     }
125
126 /**
127  * This method tries to acquire the lock but waits for waitTime in milliseconds for
128  * the lock to be acquired. If the lock is available, the invoking
129  * thread proceeds else it ends up waiting for the duration of waitTime. After that
130  * if the lock is still no available TimedOutException is thrown. If the
131  * invoking thread has already acquired this lock and tries to acquire it again the
132  * lock object allows it to acquire it again.
133  * <p>
134  * @param waitTime time to wait in milliseconds to acquire the lock
135  * @throws TimedOutException thrown if the lock is not acquired within the timeout
136  * parameter specified.
137  * @throws InterruptedException thrown if the calling thread is interrupted during
138  * the execution of acquire()
139  */

140     public synchronized void acquireLock( long waitTime) throws
141                             InterruptedException JavaDoc, TimedoutException
142     {
143         if (tryGetLock() == false && waitTime != 0) {
144             if( waitTime == -1)
145                 while(! tryGetLock())
146                     wait();
147             else {
148                 boolean isWaiting = true;
149                 long startTime = System.currentTimeMillis();
150                 long timeRemaining = waitTime;
151                 while( isWaiting) {
152                     wait( timeRemaining);
153                     if( tryGetLock())
154                         return;
155                     timeRemaining = startTime + waitTime - System.currentTimeMillis();
156                     isWaiting = (timeRemaining > 0);
157                 }
158                 throw new TimedoutException();
159             }
160         }
161     }
162
163 // synchronized not needed since this method is only called
164
// from other methods which are synchronized
165

166 // private synchronized boolean tryGetLock() {
167
private boolean tryGetLock() {
168         Thread JavaDoc t = Thread.currentThread();
169         if( owner == null) {
170             owner = t;
171             lockCount = 1;
172             return true;
173         }
174         if( owner == t) {
175             ++lockCount;
176             return true;
177         }
178         return false;
179     }
180
181 /**
182  * This method tries to release the lock and notify other waiting threads that the
183  * lock is available to be acquired.
184  * If the invoking thread has already acquired the lock multiple times then this
185  * method will not notify any waiting threads. In this scenario the invoking thread
186  * should call release() as many times on the lock object as acquire() was invoked,
187  * only after that other threads waiting for this lock will be notified.
188  * <p>
189  */

190     public synchronized void releaseLock() {
191         if(!owner.equals( Thread.currentThread()))
192             throw new IllegalMonitorStateException JavaDoc();
193         if(--lockCount == 0) {
194             owner = null;
195           notify();
196     }
197     }
198
199 /**
200  * This method can be used to test if a lock has been acquired/in use.
201  * <p>
202  * @return <code>true</code> if lock is still available else <code>false</code>
203  */

204     public synchronized boolean isLocked() { return (owner != null); }
205
206 /**
207  * This method can be used to get the thread object that is the owner of the lock.
208  * <p>
209  * @return the owner of the lock
210  */

211     public Thread JavaDoc getOwner() { return this.owner; }
212 }
213
214
Popular Tags