From: <jbo...@li...> - 2006-04-27 09:00:56
|
Author: mar...@jb... Date: 2006-04-27 05:00:47 -0400 (Thu, 27 Apr 2006) New Revision: 3991 Added: labs/jbossrules/trunk/drools-core/src/main/java/org/drools/util/concurrent/ labs/jbossrules/trunk/drools-core/src/main/java/org/drools/util/concurrent/locks/ labs/jbossrules/trunk/drools-core/src/main/java/org/drools/util/concurrent/locks/Lock.java labs/jbossrules/trunk/drools-core/src/main/java/org/drools/util/concurrent/locks/ReentrantLock.java Log: -Added in a stripped Lock implementation from concurrent backport Added: labs/jbossrules/trunk/drools-core/src/main/java/org/drools/util/concurrent/locks/Lock.java =================================================================== --- labs/jbossrules/trunk/drools-core/src/main/java/org/drools/util/concurrent/locks/Lock.java 2006-04-27 05:25:16 UTC (rev 3990) +++ labs/jbossrules/trunk/drools-core/src/main/java/org/drools/util/concurrent/locks/Lock.java 2006-04-27 09:00:47 UTC (rev 3991) @@ -0,0 +1,243 @@ +/* + * Written by Doug Lea with assistance from members of JCP JSR-166 + * Expert Group and released to the public domain, as explained at + * http://creativecommons.org/licenses/publicdomain + */ + +package org.drools.util.concurrent.locks; + +//import edu.emory.mathcs.backport.java.util.concurrent.locks.*; // for javadoc (till 6280605 is fixed) +//import edu.emory.mathcs.backport.java.util.concurrent.TimeUnit; + +/** + * <tt>Lock</tt> implementations provide more extensive locking + * operations than can be obtained using <tt>synchronized</tt> methods + * and statements. They allow more flexible structuring, may have + * quite different properties, and may support multiple associated + * {@link Condition} objects. + * + * <p>A lock is a tool for controlling access to a shared resource by + * multiple threads. Commonly, a lock provides exclusive access to a + * shared resource: only one thread at a time can acquire the lock and + * all access to the shared resource requires that the lock be + * acquired first. However, some locks may allow concurrent access to + * a shared resource, such as the read lock of a {@link + * ReadWriteLock}. + * + * <p>The use of <tt>synchronized</tt> methods or statements provides + * access to the implicit monitor lock associated with every object, but + * forces all lock acquisition and release to occur in a block-structured way: + * when multiple locks are acquired they must be released in the opposite + * order, and all locks must be released in the same lexical scope in which + * they were acquired. + * + * <p>While the scoping mechanism for <tt>synchronized</tt> methods + * and statements makes it much easier to program with monitor locks, + * and helps avoid many common programming errors involving locks, + * there are occasions where you need to work with locks in a more + * flexible way. For example, some algorithms for traversing + * concurrently accessed data structures require the use of + * "hand-over-hand" or "chain locking": you + * acquire the lock of node A, then node B, then release A and acquire + * C, then release B and acquire D and so on. Implementations of the + * <tt>Lock</tt> interface enable the use of such techniques by + * allowing a lock to be acquired and released in different scopes, + * and allowing multiple locks to be acquired and released in any + * order. + * + * <p>With this increased flexibility comes additional + * responsibility. The absence of block-structured locking removes the + * automatic release of locks that occurs with <tt>synchronized</tt> + * methods and statements. In most cases, the following idiom + * should be used: + * + * <pre><tt> Lock l = ...; + * l.lock(); + * try { + * // access the resource protected by this lock + * } finally { + * l.unlock(); + * } + * </tt></pre> + * + * When locking and unlocking occur in different scopes, care must be + * taken to ensure that all code that is executed while the lock is + * held is protected by try-finally or try-catch to ensure that the + * lock is released when necessary. + * + * <p><tt>Lock</tt> implementations provide additional functionality + * over the use of <tt>synchronized</tt> methods and statements by + * providing a non-blocking attempt to acquire a lock ({@link + * #tryLock()}), an attempt to acquire the lock that can be + * interrupted ({@link #lockInterruptibly}, and an attempt to acquire + * the lock that can timeout ({@link #tryLock(long, TimeUnit)}). + * + * <p>A <tt>Lock</tt> class can also provide behavior and semantics + * that is quite different from that of the implicit monitor lock, + * such as guaranteed ordering, non-reentrant usage, or deadlock + * detection. If an implementation provides such specialized semantics + * then the implementation must document those semantics. + * + * <p>Note that <tt>Lock</tt> instances are just normal objects and can + * themselves be used as the target in a <tt>synchronized</tt> statement. + * Acquiring the + * monitor lock of a <tt>Lock</tt> instance has no specified relationship + * with invoking any of the {@link #lock} methods of that instance. + * It is recommended that to avoid confusion you never use <tt>Lock</tt> + * instances in this way, except within their own implementation. + * + * <p>Except where noted, passing a <tt>null</tt> value for any + * parameter will result in a {@link NullPointerException} being + * thrown. + * + * <h3>Memory Synchronization</h3> + * <p>All <tt>Lock</tt> implementations <em>must</em> enforce the same + * memory synchronization semantics as provided by the built-in monitor + * lock, as described in <a href="http://java.sun.com/docs/books/jls/"> + * The Java Language Specification, Third Edition (17.4 Memory Model)</a>: + * <ul> + * <li>A successful <tt>lock</tt> operation has the same memory + * synchronization effects as a successful <em>Lock</em> action. + * <li>A successful <tt>unlock</tt> operation has the same + * memory synchronization effects as a successful <em>Unlock</em> action. + * </ul> + * + * Unsuccessful locking and unlocking operations, and reentrant + * locking/unlocking operations, do not require any memory + * synchronization effects. + * + * <h3>Implementation Considerations</h3> + * + * <p> The three forms of lock acquisition (interruptible, + * non-interruptible, and timed) may differ in their performance + * characteristics, ordering guarantees, or other implementation + * qualities. Further, the ability to interrupt the <em>ongoing</em> + * acquisition of a lock may not be available in a given <tt>Lock</tt> + * class. Consequently, an implementation is not required to define + * exactly the same guarantees or semantics for all three forms of + * lock acquisition, nor is it required to support interruption of an + * ongoing lock acquisition. An implementation is required to clearly + * document the semantics and guarantees provided by each of the + * locking methods. It must also obey the interruption semantics as + * defined in this interface, to the extent that interruption of lock + * acquisition is supported: which is either totally, or only on + * method entry. + * + * <p>As interruption generally implies cancellation, and checks for + * interruption are often infrequent, an implementation can favor responding + * to an interrupt over normal method return. This is true even if it can be + * shown that the interrupt occurred after another action may have unblocked + * the thread. An implementation should document this behavior. + * + * + * @see ReentrantLock + * @see Condition + * @see ReadWriteLock + * + * @since 1.5 + * @author Doug Lea + * + */ +public interface Lock { + + /** + * Acquires the lock. + * <p>If the lock is not available then + * the current thread becomes disabled for thread scheduling + * purposes and lies dormant until the lock has been acquired. + * <p><b>Implementation Considerations</b> + * <p>A <tt>Lock</tt> implementation may be able to detect + * erroneous use of the lock, such as an invocation that would cause + * deadlock, and may throw an (unchecked) exception in such circumstances. + * The circumstances and the exception type must be documented by that + * <tt>Lock</tt> implementation. + */ + void lock(); + + /** + * Acquires the lock unless the current thread is + * {@link Thread#interrupt interrupted}. + * <p>Acquires the lock if it is available and returns immediately. + * <p>If the lock is not available then + * the current thread becomes disabled for thread scheduling + * purposes and lies dormant until one of two things happens: + * <ul> + * <li>The lock is acquired by the current thread; or + * <li>Some other thread {@link Thread#interrupt interrupts} the current + * thread, and interruption of lock acquisition is supported. + * </ul> + * <p>If the current thread: + * <ul> + * <li>has its interrupted status set on entry to this method; or + * <li>is {@link Thread#interrupt interrupted} while acquiring + * the lock, and interruption of lock acquisition is supported, + * </ul> + * then {@link InterruptedException} is thrown and the current thread's + * interrupted status is cleared. + * + * <p><b>Implementation Considerations</b> + * + * <p>The ability to interrupt a lock acquisition in some + * implementations may not be possible, and if possible may be an + * expensive operation. The programmer should be aware that this + * may be the case. An implementation should document when this is + * the case. + * + * <p>An implementation can favor responding to an interrupt over + * normal method return. + * + * <p>A <tt>Lock</tt> implementation may be able to detect + * erroneous use of the lock, such as an invocation that would + * cause deadlock, and may throw an (unchecked) exception in such + * circumstances. The circumstances and the exception type must + * be documented by that <tt>Lock</tt> implementation. + * + * @throws InterruptedException if the current thread is interrupted + * while acquiring the lock (and interruption of lock acquisition is + * supported). + * + * @see Thread#interrupt + */ + void lockInterruptibly() throws InterruptedException; + + + /** + * Acquires the lock only if it is free at the time of invocation. + * <p>Acquires the lock if it is available and returns immediately + * with the value <tt>true</tt>. + * If the lock is not available then this method will return + * immediately with the value <tt>false</tt>. + * <p>A typical usage idiom for this method would be: + * <pre> + * Lock lock = ...; + * if (lock.tryLock()) { + * try { + * // manipulate protected state + * } finally { + * lock.unlock(); + * } + * } else { + * // perform alternative actions + * } + * </pre> + * This usage ensures that the lock is unlocked if it was acquired, and + * doesn't try to unlock if the lock was not acquired. + * + * @return <tt>true</tt> if the lock was acquired and <tt>false</tt> + * otherwise. + */ + boolean tryLock(); + + /** + * Releases the lock. + * <p><b>Implementation Considerations</b> + * <p>A <tt>Lock</tt> implementation will usually impose + * restrictions on which thread can release a lock (typically only the + * holder of the lock can release it) and may throw + * an (unchecked) exception if the restriction is violated. + * Any restrictions and the exception + * type must be documented by that <tt>Lock</tt> implementation. + */ + void unlock(); + +} Added: labs/jbossrules/trunk/drools-core/src/main/java/org/drools/util/concurrent/locks/ReentrantLock.java =================================================================== --- labs/jbossrules/trunk/drools-core/src/main/java/org/drools/util/concurrent/locks/ReentrantLock.java 2006-04-27 05:25:16 UTC (rev 3990) +++ labs/jbossrules/trunk/drools-core/src/main/java/org/drools/util/concurrent/locks/ReentrantLock.java 2006-04-27 09:00:47 UTC (rev 3991) @@ -0,0 +1,466 @@ +/* + * Written by Doug Lea with assistance from members of JCP JSR-166 + * Expert Group and released to the public domain, as explained at + * http://creativecommons.org/licenses/publicdomain + */ + +package org.drools.util.concurrent.locks; + +import java.util.Collection; + +/** + * This is a stripped down version of jdk1.5 ReentrantLock. + * All the condition and wait stuff has been removed + * + * @since 1.5 + * @author Doug Lea + * @author Dawid Kurzyniec + */ +public class ReentrantLock implements Lock, java.io.Serializable { + private static final long serialVersionUID = 7373984872572414699L; + + private final NonfairSync sync; + + final static class NonfairSync { + private static final long serialVersionUID = 7316153563782823691L; + + protected transient Thread owner_ = null; + protected transient int holds_ = 0; + + final void incHolds() { + int nextHolds = ++holds_; + if (nextHolds < 0) + throw new Error("Maximum lock count exceeded"); + holds_ = nextHolds; + } + + public boolean tryLock() { + Thread caller = Thread.currentThread(); + synchronized (this) { + if (owner_ == null) { + owner_ = caller; + holds_ = 1; + return true; + } + else if (caller == owner_) { + incHolds(); + return true; + } + } + return false; + } + + public synchronized int getHoldCount() { + return isHeldByCurrentThread() ? holds_ : 0; + } + + public synchronized boolean isHeldByCurrentThread() { + return holds_ > 0 && Thread.currentThread() == owner_; + } + + public synchronized boolean isLocked() { + return owner_ != null; + } + + protected synchronized Thread getOwner() { + return owner_; + } + + public boolean hasQueuedThreads() { + throw new UnsupportedOperationException("Use FAIR version"); + } + + public int getQueueLength() { + throw new UnsupportedOperationException("Use FAIR version"); + } + + public Collection getQueuedThreads() { + throw new UnsupportedOperationException("Use FAIR version"); + } + + public boolean isQueued(Thread thread) { + throw new UnsupportedOperationException("Use FAIR version"); + } + + public void lock() { + Thread caller = Thread.currentThread(); + synchronized (this) { + if (owner_ == null) { + owner_ = caller; + holds_ = 1; + return; + } + else if (caller == owner_) { + incHolds(); + return; + } + else { + boolean wasInterrupted = Thread.interrupted(); + try { + while (true) { + try { + wait(); + } + catch (InterruptedException e) { + wasInterrupted = true; + // no need to notify; if we were signalled, we + // will act as signalled, ignoring the + // interruption + } + if (owner_ == null) { + owner_ = caller; + holds_ = 1; + return; + } + } + } + finally { + if (wasInterrupted) Thread.currentThread().interrupt(); + } + } + } + } + + public void lockInterruptibly() throws InterruptedException { + if (Thread.interrupted()) throw new InterruptedException(); + Thread caller = Thread.currentThread(); + synchronized (this) { + if (owner_ == null) { + owner_ = caller; + holds_ = 1; + return; + } + else if (caller == owner_) { + incHolds(); + return; + } + else { + try { + do { wait(); } while (owner_ != null); + owner_ = caller; + holds_ = 1; + return; + } + catch (InterruptedException ex) { + if (owner_ == null) notify(); + throw ex; + } + } + } + } + + public synchronized void unlock() { + if (Thread.currentThread() != owner_) + throw new IllegalMonitorStateException("Not owner"); + + if (--holds_ == 0) { + owner_ = null; + notify(); + } + } + } + + /** + * Creates an instance of <tt>ReentrantLock</tt>. + * This is equivalent to using <tt>ReentrantLock(false)</tt>. + */ + public ReentrantLock() { + sync = new NonfairSync(); + } + + /** + * Acquires the lock. + * + * <p>Acquires the lock if it is not held by another thread and returns + * immediately, setting the lock hold count to one. + * + * <p>If the current thread + * already holds the lock then the hold count is incremented by one and + * the method returns immediately. + * + * <p>If the lock is held by another thread then the + * current thread becomes disabled for thread scheduling + * purposes and lies dormant until the lock has been acquired, + * at which time the lock hold count is set to one. + */ + public void lock() { + sync.lock(); + } + + /** + * Acquires the lock unless the current thread is + * {@link Thread#interrupt interrupted}. + * + * <p>Acquires the lock if it is not held by another thread and returns + * immediately, setting the lock hold count to one. + * + * <p>If the current thread already holds this lock then the hold count + * is incremented by one and the method returns immediately. + * + * <p>If the lock is held by another thread then the + * current thread becomes disabled for thread scheduling + * purposes and lies dormant until one of two things happens: + * + * <ul> + * + * <li>The lock is acquired by the current thread; or + * + * <li>Some other thread {@link Thread#interrupt interrupts} the current + * thread. + * + * </ul> + * + * <p>If the lock is acquired by the current thread then the lock hold + * count is set to one. + * + * <p>If the current thread: + * + * <ul> + * + * <li>has its interrupted status set on entry to this method; or + * + * <li>is {@link Thread#interrupt interrupted} while acquiring + * the lock, + * + * </ul> + * + * then {@link InterruptedException} is thrown and the current thread's + * interrupted status is cleared. + * + * <p>In this implementation, as this method is an explicit interruption + * point, preference is + * given to responding to the interrupt over normal or reentrant + * acquisition of the lock. + * + * @throws InterruptedException if the current thread is interrupted + */ + public void lockInterruptibly() throws InterruptedException { + sync.lockInterruptibly(); + } + + /** + * Acquires the lock only if it is not held by another thread at the time + * of invocation. + * + * <p>Acquires the lock if it is not held by another thread and + * returns immediately with the value <tt>true</tt>, setting the + * lock hold count to one. Even when this lock has been set to use a + * fair ordering policy, a call to <tt>tryLock()</tt> <em>will</em> + * immediately acquire the lock if it is available, whether or not + * other threads are currently waiting for the lock. + * This "barging" behavior can be useful in certain + * circumstances, even though it breaks fairness. If you want to honor + * the fairness setting for this lock, then use + * {@link #tryLock(long, TimeUnit) tryLock(0, TimeUnit.SECONDS) } + * which is almost equivalent (it also detects interruption). + * + * <p> If the current thread + * already holds this lock then the hold count is incremented by one and + * the method returns <tt>true</tt>. + * + * <p>If the lock is held by another thread then this method will return + * immediately with the value <tt>false</tt>. + * + * @return <tt>true</tt> if the lock was free and was acquired by the + * current thread, or the lock was already held by the current thread; and + * <tt>false</tt> otherwise. + */ + public boolean tryLock() { + return sync.tryLock(); + } + + + /** + * Attempts to release this lock. + * + * <p>If the current thread is the + * holder of this lock then the hold count is decremented. If the + * hold count is now zero then the lock is released. If the + * current thread is not the holder of this lock then {@link + * IllegalMonitorStateException} is thrown. + * @throws IllegalMonitorStateException if the current thread does not + * hold this lock. + */ + public void unlock() { + sync.unlock(); + } + + /** + * Queries the number of holds on this lock by the current thread. + * + * <p>A thread has a hold on a lock for each lock action that is not + * matched by an unlock action. + * + * <p>The hold count information is typically only used for testing and + * debugging purposes. For example, if a certain section of code should + * not be entered with the lock already held then we can assert that + * fact: + * + * <pre> + * class X { + * ReentrantLock lock = new ReentrantLock(); + * // ... + * public void m() { + * assert lock.getHoldCount() == 0; + * lock.lock(); + * try { + * // ... method body + * } finally { + * lock.unlock(); + * } + * } + * } + * </pre> + * + * @return the number of holds on this lock by the current thread, + * or zero if this lock is not held by the current thread. + */ + public int getHoldCount() { + return sync.getHoldCount(); + } + + /** + * Queries if this lock is held by the current thread. + * + * <p>Analogous to the {@link Thread#holdsLock} method for built-in + * monitor locks, this method is typically used for debugging and + * testing. For example, a method that should only be called while + * a lock is held can assert that this is the case: + * + * <pre> + * class X { + * ReentrantLock lock = new ReentrantLock(); + * // ... + * + * public void m() { + * assert lock.isHeldByCurrentThread(); + * // ... method body + * } + * } + * </pre> + * + * <p>It can also be used to ensure that a reentrant lock is used + * in a non-reentrant manner, for example: + * + * <pre> + * class X { + * ReentrantLock lock = new ReentrantLock(); + * // ... + * + * public void m() { + * assert !lock.isHeldByCurrentThread(); + * lock.lock(); + * try { + * // ... method body + * } finally { + * lock.unlock(); + * } + * } + * } + * </pre> + * @return <tt>true</tt> if current thread holds this lock and + * <tt>false</tt> otherwise. + */ + public boolean isHeldByCurrentThread() { + return sync.isHeldByCurrentThread(); + } + + /** + * Queries if this lock is held by any thread. This method is + * designed for use in monitoring of the system state, + * not for synchronization control. + * @return <tt>true</tt> if any thread holds this lock and + * <tt>false</tt> otherwise. + */ + public boolean isLocked() { + return sync.isLocked(); + } + + /** + * <tt>null</tt> if not owned. When this method is called by a + * thread that is not the owner, the return value reflects a + * best-effort approximation of current lock status. For example, + * the owner may be momentarily <tt>null</tt> even if there are + * threads trying to acquire the lock but have not yet done so. + * This method is designed to facilitate construction of + * subclasses that provide more extensive lock monitoring + * facilities. + * + * @return the owner, or <tt>null</tt> if not owned + */ + protected Thread getOwner() { + return sync.getOwner(); + } + + /** + * Queries whether any threads are waiting to acquire this lock. Note that + * because cancellations may occur at any time, a <tt>true</tt> + * return does not guarantee that any other thread will ever + * acquire this lock. This method is designed primarily for use in + * monitoring of the system state. + * + * @return true if there may be other threads waiting to acquire + * the lock. + */ + public final boolean hasQueuedThreads() { + return sync.hasQueuedThreads(); + } + + + /** + * Queries whether the given thread is waiting to acquire this + * lock. Note that because cancellations may occur at any time, a + * <tt>true</tt> return does not guarantee that this thread + * will ever acquire this lock. This method is designed primarily for use + * in monitoring of the system state. + * + * @param thread the thread + * @return true if the given thread is queued waiting for this lock. + * @throws NullPointerException if thread is null + */ + public final boolean hasQueuedThread(Thread thread) { + return sync.isQueued(thread); + } + + + /** + * Returns an estimate of the number of threads waiting to + * acquire this lock. The value is only an estimate because the number of + * threads may change dynamically while this method traverses + * internal data structures. This method is designed for use in + * monitoring of the system state, not for synchronization + * control. + * @return the estimated number of threads waiting for this lock + */ + public final int getQueueLength() { + return sync.getQueueLength(); + } + + /** + * Returns a collection containing threads that may be waiting to + * acquire this lock. Because the actual set of threads may change + * dynamically while constructing this result, the returned + * collection is only a best-effort estimate. The elements of the + * returned collection are in no particular order. This method is + * designed to facilitate construction of subclasses that provide + * more extensive monitoring facilities. + * @return the collection of threads + */ + protected Collection getQueuedThreads() { + return sync.getQueuedThreads(); + } + + /** + * Returns a string identifying this lock, as well as its lock + * state. The state, in brackets, includes either the String + * "Unlocked" or the String "Locked by" + * followed by the {@link Thread#getName} of the owning thread. + * @return a string identifying this lock, as well as its lock state. + */ + public String toString() { + Thread o = getOwner(); + return super.toString() + ((o == null) ? + "[Unlocked]" : + "[Locked by thread " + o.getName() + "]"); + } +} |