001: /*
002: * Written by Doug Lea with assistance from members of JCP JSR-166
003: * Expert Group and released to the public domain, as explained at
004: * http://creativecommons.org/licenses/publicdomain
005: */
006:
007: package org.drools.util.concurrent.locks;
008:
009: import java.io.Serializable;
010: import java.util.Collection;
011:
012: /**
013: * This is a stripped down version of jdk1.5 ReentrantLock.
014: * All the condition and wait stuff has been removed
015: *
016: * @since 1.5
017: * @author Doug Lea
018: * @author Dawid Kurzyniec
019: */
020: public class ReentrantLock implements Lock, java.io.Serializable {
021: private static final long serialVersionUID = 400L;
022:
023: private final NonfairSync sync;
024:
025: final static class NonfairSync implements Serializable {
026: private static final long serialVersionUID = 400L;
027:
028: protected transient Thread owner_ = null;
029: protected transient int holds_ = 0;
030:
031: final void incHolds() {
032: final int nextHolds = ++this .holds_;
033: if (nextHolds < 0) {
034: throw new Error("Maximum lock count exceeded");
035: }
036: this .holds_ = nextHolds;
037: }
038:
039: public boolean tryLock() {
040: final Thread caller = Thread.currentThread();
041: synchronized (this ) {
042: if (this .owner_ == null) {
043: this .owner_ = caller;
044: this .holds_ = 1;
045: return true;
046: } else if (caller == this .owner_) {
047: incHolds();
048: return true;
049: }
050: }
051: return false;
052: }
053:
054: public synchronized int getHoldCount() {
055: return isHeldByCurrentThread() ? this .holds_ : 0;
056: }
057:
058: public synchronized boolean isHeldByCurrentThread() {
059: return this .holds_ > 0
060: && Thread.currentThread() == this .owner_;
061: }
062:
063: public synchronized boolean isLocked() {
064: return this .owner_ != null;
065: }
066:
067: protected synchronized Thread getOwner() {
068: return this .owner_;
069: }
070:
071: public boolean hasQueuedThreads() {
072: throw new UnsupportedOperationException("Use FAIR version");
073: }
074:
075: public int getQueueLength() {
076: throw new UnsupportedOperationException("Use FAIR version");
077: }
078:
079: public Collection getQueuedThreads() {
080: throw new UnsupportedOperationException("Use FAIR version");
081: }
082:
083: public boolean isQueued(final Thread thread) {
084: throw new UnsupportedOperationException("Use FAIR version");
085: }
086:
087: public void lock() {
088: final Thread caller = Thread.currentThread();
089: synchronized (this ) {
090: if (this .owner_ == null) {
091: this .owner_ = caller;
092: this .holds_ = 1;
093: return;
094: } else if (caller == this .owner_) {
095: incHolds();
096: return;
097: } else {
098: boolean wasInterrupted = Thread.interrupted();
099: try {
100: while (true) {
101: try {
102: wait();
103: } catch (final InterruptedException e) {
104: wasInterrupted = true;
105: // no need to notify; if we were signalled, we
106: // will act as signalled, ignoring the
107: // interruption
108: }
109: if (this .owner_ == null) {
110: this .owner_ = caller;
111: this .holds_ = 1;
112: return;
113: }
114: }
115: } finally {
116: if (wasInterrupted) {
117: Thread.currentThread().interrupt();
118: }
119: }
120: }
121: }
122: }
123:
124: public void lockInterruptibly() throws InterruptedException {
125: if (Thread.interrupted()) {
126: throw new InterruptedException();
127: }
128: final Thread caller = Thread.currentThread();
129: synchronized (this ) {
130: if (this .owner_ == null) {
131: this .owner_ = caller;
132: this .holds_ = 1;
133: return;
134: } else if (caller == this .owner_) {
135: incHolds();
136: return;
137: } else {
138: try {
139: do {
140: wait();
141: } while (this .owner_ != null);
142: this .owner_ = caller;
143: this .holds_ = 1;
144: return;
145: } catch (final InterruptedException ex) {
146: if (this .owner_ == null) {
147: notify();
148: }
149: throw ex;
150: }
151: }
152: }
153: }
154:
155: public synchronized void unlock() {
156: if (Thread.currentThread() != this .owner_) {
157: throw new IllegalMonitorStateException("Not owner");
158: }
159:
160: if (--this .holds_ == 0) {
161: this .owner_ = null;
162: notify();
163: }
164: }
165: }
166:
167: /**
168: * Creates an instance of <tt>ReentrantLock</tt>.
169: * This is equivalent to using <tt>ReentrantLock(false)</tt>.
170: */
171: public ReentrantLock() {
172: this .sync = new NonfairSync();
173: }
174:
175: /**
176: * Acquires the lock.
177: *
178: * <p>Acquires the lock if it is not held by another thread and returns
179: * immediately, setting the lock hold count to one.
180: *
181: * <p>If the current thread
182: * already holds the lock then the hold count is incremented by one and
183: * the method returns immediately.
184: *
185: * <p>If the lock is held by another thread then the
186: * current thread becomes disabled for thread scheduling
187: * purposes and lies dormant until the lock has been acquired,
188: * at which time the lock hold count is set to one.
189: */
190: public void lock() {
191: this .sync.lock();
192: }
193:
194: /**
195: * Acquires the lock unless the current thread is
196: * {@link Thread#interrupt interrupted}.
197: *
198: * <p>Acquires the lock if it is not held by another thread and returns
199: * immediately, setting the lock hold count to one.
200: *
201: * <p>If the current thread already holds this lock then the hold count
202: * is incremented by one and the method returns immediately.
203: *
204: * <p>If the lock is held by another thread then the
205: * current thread becomes disabled for thread scheduling
206: * purposes and lies dormant until one of two things happens:
207: *
208: * <ul>
209: *
210: * <li>The lock is acquired by the current thread; or
211: *
212: * <li>Some other thread {@link Thread#interrupt interrupts} the current
213: * thread.
214: *
215: * </ul>
216: *
217: * <p>If the lock is acquired by the current thread then the lock hold
218: * count is set to one.
219: *
220: * <p>If the current thread:
221: *
222: * <ul>
223: *
224: * <li>has its interrupted status set on entry to this method; or
225: *
226: * <li>is {@link Thread#interrupt interrupted} while acquiring
227: * the lock,
228: *
229: * </ul>
230: *
231: * then {@link InterruptedException} is thrown and the current thread's
232: * interrupted status is cleared.
233: *
234: * <p>In this implementation, as this method is an explicit interruption
235: * point, preference is
236: * given to responding to the interrupt over normal or reentrant
237: * acquisition of the lock.
238: *
239: * @throws InterruptedException if the current thread is interrupted
240: */
241: public void lockInterruptibly() throws InterruptedException {
242: this .sync.lockInterruptibly();
243: }
244:
245: /**
246: * Acquires the lock only if it is not held by another thread at the time
247: * of invocation.
248: *
249: * <p>Acquires the lock if it is not held by another thread and
250: * returns immediately with the value <tt>true</tt>, setting the
251: * lock hold count to one. Even when this lock has been set to use a
252: * fair ordering policy, a call to <tt>tryLock()</tt> <em>will</em>
253: * immediately acquire the lock if it is available, whether or not
254: * other threads are currently waiting for the lock.
255: * This "barging" behavior can be useful in certain
256: * circumstances, even though it breaks fairness. If you want to honor
257: * the fairness setting for this lock, then use
258: * {@link #tryLock(long, TimeUnit) tryLock(0, TimeUnit.SECONDS) }
259: * which is almost equivalent (it also detects interruption).
260: *
261: * <p> If the current thread
262: * already holds this lock then the hold count is incremented by one and
263: * the method returns <tt>true</tt>.
264: *
265: * <p>If the lock is held by another thread then this method will return
266: * immediately with the value <tt>false</tt>.
267: *
268: * @return <tt>true</tt> if the lock was free and was acquired by the
269: * current thread, or the lock was already held by the current thread; and
270: * <tt>false</tt> otherwise.
271: */
272: public boolean tryLock() {
273: return this .sync.tryLock();
274: }
275:
276: /**
277: * Attempts to release this lock.
278: *
279: * <p>If the current thread is the
280: * holder of this lock then the hold count is decremented. If the
281: * hold count is now zero then the lock is released. If the
282: * current thread is not the holder of this lock then {@link
283: * IllegalMonitorStateException} is thrown.
284: * @throws IllegalMonitorStateException if the current thread does not
285: * hold this lock.
286: */
287: public void unlock() {
288: this .sync.unlock();
289: }
290:
291: /**
292: * Queries the number of holds on this lock by the current thread.
293: *
294: * <p>A thread has a hold on a lock for each lock action that is not
295: * matched by an unlock action.
296: *
297: * <p>The hold count information is typically only used for testing and
298: * debugging purposes. For example, if a certain section of code should
299: * not be entered with the lock already held then we can assert that
300: * fact:
301: *
302: * <pre>
303: * class X {
304: * ReentrantLock lock = new ReentrantLock();
305: * // ...
306: * public void m() {
307: * assert lock.getHoldCount() == 0;
308: * lock.lock();
309: * try {
310: * // ... method body
311: * } finally {
312: * lock.unlock();
313: * }
314: * }
315: * }
316: * </pre>
317: *
318: * @return the number of holds on this lock by the current thread,
319: * or zero if this lock is not held by the current thread.
320: */
321: public int getHoldCount() {
322: return this .sync.getHoldCount();
323: }
324:
325: /**
326: * Queries if this lock is held by the current thread.
327: *
328: * <p>Analogous to the {@link Thread#holdsLock} method for built-in
329: * monitor locks, this method is typically used for debugging and
330: * testing. For example, a method that should only be called while
331: * a lock is held can assert that this is the case:
332: *
333: * <pre>
334: * class X {
335: * ReentrantLock lock = new ReentrantLock();
336: * // ...
337: *
338: * public void m() {
339: * assert lock.isHeldByCurrentThread();
340: * // ... method body
341: * }
342: * }
343: * </pre>
344: *
345: * <p>It can also be used to ensure that a reentrant lock is used
346: * in a non-reentrant manner, for example:
347: *
348: * <pre>
349: * class X {
350: * ReentrantLock lock = new ReentrantLock();
351: * // ...
352: *
353: * public void m() {
354: * assert !lock.isHeldByCurrentThread();
355: * lock.lock();
356: * try {
357: * // ... method body
358: * } finally {
359: * lock.unlock();
360: * }
361: * }
362: * }
363: * </pre>
364: * @return <tt>true</tt> if current thread holds this lock and
365: * <tt>false</tt> otherwise.
366: */
367: public boolean isHeldByCurrentThread() {
368: return this .sync.isHeldByCurrentThread();
369: }
370:
371: /**
372: * Queries if this lock is held by any thread. This method is
373: * designed for use in monitoring of the system state,
374: * not for synchronization control.
375: * @return <tt>true</tt> if any thread holds this lock and
376: * <tt>false</tt> otherwise.
377: */
378: public boolean isLocked() {
379: return this .sync.isLocked();
380: }
381:
382: /**
383: * <tt>null</tt> if not owned. When this method is called by a
384: * thread that is not the owner, the return value reflects a
385: * best-effort approximation of current lock status. For example,
386: * the owner may be momentarily <tt>null</tt> even if there are
387: * threads trying to acquire the lock but have not yet done so.
388: * This method is designed to facilitate construction of
389: * subclasses that provide more extensive lock monitoring
390: * facilities.
391: *
392: * @return the owner, or <tt>null</tt> if not owned
393: */
394: protected Thread getOwner() {
395: return this .sync.getOwner();
396: }
397:
398: /**
399: * Queries whether any threads are waiting to acquire this lock. Note that
400: * because cancellations may occur at any time, a <tt>true</tt>
401: * return does not guarantee that any other thread will ever
402: * acquire this lock. This method is designed primarily for use in
403: * monitoring of the system state.
404: *
405: * @return true if there may be other threads waiting to acquire
406: * the lock.
407: */
408: public final boolean hasQueuedThreads() {
409: return this .sync.hasQueuedThreads();
410: }
411:
412: /**
413: * Queries whether the given thread is waiting to acquire this
414: * lock. Note that because cancellations may occur at any time, a
415: * <tt>true</tt> return does not guarantee that this thread
416: * will ever acquire this lock. This method is designed primarily for use
417: * in monitoring of the system state.
418: *
419: * @param thread the thread
420: * @return true if the given thread is queued waiting for this lock.
421: * @throws NullPointerException if thread is null
422: */
423: public final boolean hasQueuedThread(final Thread thread) {
424: return this .sync.isQueued(thread);
425: }
426:
427: /**
428: * Returns an estimate of the number of threads waiting to
429: * acquire this lock. The value is only an estimate because the number of
430: * threads may change dynamically while this method traverses
431: * internal data structures. This method is designed for use in
432: * monitoring of the system state, not for synchronization
433: * control.
434: * @return the estimated number of threads waiting for this lock
435: */
436: public final int getQueueLength() {
437: return this .sync.getQueueLength();
438: }
439:
440: /**
441: * Returns a collection containing threads that may be waiting to
442: * acquire this lock. Because the actual set of threads may change
443: * dynamically while constructing this result, the returned
444: * collection is only a best-effort estimate. The elements of the
445: * returned collection are in no particular order. This method is
446: * designed to facilitate construction of subclasses that provide
447: * more extensive monitoring facilities.
448: * @return the collection of threads
449: */
450: protected Collection getQueuedThreads() {
451: return this .sync.getQueuedThreads();
452: }
453:
454: /**
455: * Returns a string identifying this lock, as well as its lock
456: * state. The state, in brackets, includes either the String
457: * "Unlocked" or the String "Locked by"
458: * followed by the {@link Thread#getName} of the owning thread.
459: * @return a string identifying this lock, as well as its lock state.
460: */
461: public String toString() {
462: final Thread o = getOwner();
463: return super .toString()
464: + ((o == null) ? "[Unlocked]" : "[Locked by thread "
465: + o.getName() + "]");
466: }
467: }
|