2 * Written by Doug Lea with assistance from members of JCP JSR-166
3 * Expert Group and released to the public domain, as explained at
4 * http://creativecommons.org/licenses/publicdomain
7 package java.util.concurrent.locks;
8 import java.util.concurrent.TimeUnit;
11 * {@code Lock} implementations provide more extensive locking
12 * operations than can be obtained using {@code synchronized} methods
13 * and statements. They allow more flexible structuring, may have
14 * quite different properties, and may support multiple associated
15 * {@link Condition} objects.
17 * <p>A lock is a tool for controlling access to a shared resource by
18 * multiple threads. Commonly, a lock provides exclusive access to a
19 * shared resource: only one thread at a time can acquire the lock and
20 * all access to the shared resource requires that the lock be
21 * acquired first. However, some locks may allow concurrent access to
22 * a shared resource, such as the read lock of a {@link ReadWriteLock}.
24 * <p>The use of {@code synchronized} methods or statements provides
25 * access to the implicit monitor lock associated with every object, but
26 * forces all lock acquisition and release to occur in a block-structured way:
27 * when multiple locks are acquired they must be released in the opposite
28 * order, and all locks must be released in the same lexical scope in which
31 * <p>While the scoping mechanism for {@code synchronized} methods
32 * and statements makes it much easier to program with monitor locks,
33 * and helps avoid many common programming errors involving locks,
34 * there are occasions where you need to work with locks in a more
35 * flexible way. For example, some algorithms for traversing
36 * concurrently accessed data structures require the use of
37 * "hand-over-hand" or "chain locking": you
38 * acquire the lock of node A, then node B, then release A and acquire
39 * C, then release B and acquire D and so on. Implementations of the
40 * {@code Lock} interface enable the use of such techniques by
41 * allowing a lock to be acquired and released in different scopes,
42 * and allowing multiple locks to be acquired and released in any
45 * <p>With this increased flexibility comes additional
46 * responsibility. The absence of block-structured locking removes the
47 * automatic release of locks that occurs with {@code synchronized}
48 * methods and statements. In most cases, the following idiom
51 * <pre><tt> Lock l = ...;
54 * // access the resource protected by this lock
60 * When locking and unlocking occur in different scopes, care must be
61 * taken to ensure that all code that is executed while the lock is
62 * held is protected by try-finally or try-catch to ensure that the
63 * lock is released when necessary.
65 * <p>{@code Lock} implementations provide additional functionality
66 * over the use of {@code synchronized} methods and statements by
67 * providing a non-blocking attempt to acquire a lock ({@link
68 * #tryLock()}), an attempt to acquire the lock that can be
69 * interrupted ({@link #lockInterruptibly}, and an attempt to acquire
70 * the lock that can timeout ({@link #tryLock(long, TimeUnit)}).
72 * <p>A {@code Lock} class can also provide behavior and semantics
73 * that is quite different from that of the implicit monitor lock,
74 * such as guaranteed ordering, non-reentrant usage, or deadlock
75 * detection. If an implementation provides such specialized semantics
76 * then the implementation must document those semantics.
78 * <p>Note that {@code Lock} instances are just normal objects and can
79 * themselves be used as the target in a {@code synchronized} statement.
81 * monitor lock of a {@code Lock} instance has no specified relationship
82 * with invoking any of the {@link #lock} methods of that instance.
83 * It is recommended that to avoid confusion you never use {@code Lock}
84 * instances in this way, except within their own implementation.
86 * <p>Except where noted, passing a {@code null} value for any
87 * parameter will result in a {@link NullPointerException} being
90 * <h3>Memory Synchronization</h3>
92 * <p>All {@code Lock} implementations <em>must</em> enforce the same
93 * memory synchronization semantics as provided by the built-in monitor
94 * lock, as described in <a href="http://java.sun.com/docs/books/jls/">
95 * The Java Language Specification, Third Edition (17.4 Memory Model)</a>:
97 * <li>A successful {@code lock} operation has the same memory
98 * synchronization effects as a successful <em>Lock</em> action.
99 * <li>A successful {@code unlock} operation has the same
100 * memory synchronization effects as a successful <em>Unlock</em> action.
103 * Unsuccessful locking and unlocking operations, and reentrant
104 * locking/unlocking operations, do not require any memory
105 * synchronization effects.
107 * <h3>Implementation Considerations</h3>
109 * <p> The three forms of lock acquisition (interruptible,
110 * non-interruptible, and timed) may differ in their performance
111 * characteristics, ordering guarantees, or other implementation
112 * qualities. Further, the ability to interrupt the <em>ongoing</em>
113 * acquisition of a lock may not be available in a given {@code Lock}
114 * class. Consequently, an implementation is not required to define
115 * exactly the same guarantees or semantics for all three forms of
116 * lock acquisition, nor is it required to support interruption of an
117 * ongoing lock acquisition. An implementation is required to clearly
118 * document the semantics and guarantees provided by each of the
119 * locking methods. It must also obey the interruption semantics as
120 * defined in this interface, to the extent that interruption of lock
121 * acquisition is supported: which is either totally, or only on
124 * <p>As interruption generally implies cancellation, and checks for
125 * interruption are often infrequent, an implementation can favor responding
126 * to an interrupt over normal method return. This is true even if it can be
127 * shown that the interrupt occurred after another action may have unblocked
128 * the thread. An implementation should document this behavior.
137 public interface Lock {
142 * <p>If the lock is not available then the current thread becomes
143 * disabled for thread scheduling purposes and lies dormant until the
144 * lock has been acquired.
146 * <p><b>Implementation Considerations</b>
148 * <p>A {@code Lock} implementation may be able to detect erroneous use
149 * of the lock, such as an invocation that would cause deadlock, and
150 * may throw an (unchecked) exception in such circumstances. The
151 * circumstances and the exception type must be documented by that
152 * {@code Lock} implementation.
157 * Acquires the lock unless the current thread is
158 * {@linkplain Thread#interrupt interrupted}.
160 * <p>Acquires the lock if it is available and returns immediately.
162 * <p>If the lock is not available then the current thread becomes
163 * disabled for thread scheduling purposes and lies dormant until
164 * one of two things happens:
167 * <li>The lock is acquired by the current thread; or
168 * <li>Some other thread {@linkplain Thread#interrupt interrupts} the
169 * current thread, and interruption of lock acquisition is supported.
172 * <p>If the current thread:
174 * <li>has its interrupted status set on entry to this method; or
175 * <li>is {@linkplain Thread#interrupt interrupted} while acquiring the
176 * lock, and interruption of lock acquisition is supported,
178 * then {@link InterruptedException} is thrown and the current thread's
179 * interrupted status is cleared.
181 * <p><b>Implementation Considerations</b>
183 * <p>The ability to interrupt a lock acquisition in some
184 * implementations may not be possible, and if possible may be an
185 * expensive operation. The programmer should be aware that this
186 * may be the case. An implementation should document when this is
189 * <p>An implementation can favor responding to an interrupt over
190 * normal method return.
192 * <p>A {@code Lock} implementation may be able to detect
193 * erroneous use of the lock, such as an invocation that would
194 * cause deadlock, and may throw an (unchecked) exception in such
195 * circumstances. The circumstances and the exception type must
196 * be documented by that {@code Lock} implementation.
198 * @throws InterruptedException if the current thread is
199 * interrupted while acquiring the lock (and interruption
200 * of lock acquisition is supported).
202 //void lockInterruptibly() throws InterruptedException;
205 * Acquires the lock only if it is free at the time of invocation.
207 * <p>Acquires the lock if it is available and returns immediately
208 * with the value {@code true}.
209 * If the lock is not available then this method will return
210 * immediately with the value {@code false}.
212 * <p>A typical usage idiom for this method would be:
215 * if (lock.tryLock()) {
217 * // manipulate protected state
222 * // perform alternative actions
225 * This usage ensures that the lock is unlocked if it was acquired, and
226 * doesn't try to unlock if the lock was not acquired.
228 * @return {@code true} if the lock was acquired and
229 * {@code false} otherwise
234 * Acquires the lock if it is free within the given waiting time and the
235 * current thread has not been {@linkplain Thread#interrupt interrupted}.
237 * <p>If the lock is available this method returns immediately
238 * with the value {@code true}.
239 * If the lock is not available then
240 * the current thread becomes disabled for thread scheduling
241 * purposes and lies dormant until one of three things happens:
243 * <li>The lock is acquired by the current thread; or
244 * <li>Some other thread {@linkplain Thread#interrupt interrupts} the
245 * current thread, and interruption of lock acquisition is supported; or
246 * <li>The specified waiting time elapses
249 * <p>If the lock is acquired then the value {@code true} is returned.
251 * <p>If the current thread:
253 * <li>has its interrupted status set on entry to this method; or
254 * <li>is {@linkplain Thread#interrupt interrupted} while acquiring
255 * the lock, and interruption of lock acquisition is supported,
257 * then {@link InterruptedException} is thrown and the current thread's
258 * interrupted status is cleared.
260 * <p>If the specified waiting time elapses then the value {@code false}
263 * less than or equal to zero, the method will not wait at all.
265 * <p><b>Implementation Considerations</b>
267 * <p>The ability to interrupt a lock acquisition in some implementations
268 * may not be possible, and if possible may
269 * be an expensive operation.
270 * The programmer should be aware that this may be the case. An
271 * implementation should document when this is the case.
273 * <p>An implementation can favor responding to an interrupt over normal
274 * method return, or reporting a timeout.
276 * <p>A {@code Lock} implementation may be able to detect
277 * erroneous use of the lock, such as an invocation that would cause
278 * deadlock, and may throw an (unchecked) exception in such circumstances.
279 * The circumstances and the exception type must be documented by that
280 * {@code Lock} implementation.
282 * @param time the maximum time to wait for the lock
283 * @param unit the time unit of the {@code time} argument
284 * @return {@code true} if the lock was acquired and {@code false}
285 * if the waiting time elapsed before the lock was acquired
287 * @throws InterruptedException if the current thread is interrupted
288 * while acquiring the lock (and interruption of lock
289 * acquisition is supported)
291 //boolean tryLock(long time, TimeUnit unit) throws InterruptedException;
296 * <p><b>Implementation Considerations</b>
298 * <p>A {@code Lock} implementation will usually impose
299 * restrictions on which thread can release a lock (typically only the
300 * holder of the lock can release it) and may throw
301 * an (unchecked) exception if the restriction is violated.
302 * Any restrictions and the exception
303 * type must be documented by that {@code Lock} implementation.
308 * Returns a new {@link Condition} instance that is bound to this
309 * {@code Lock} instance.
311 * <p>Before waiting on the condition the lock must be held by the
313 * A call to {@link Condition#await()} will atomically release the lock
314 * before waiting and re-acquire the lock before the wait returns.
316 * <p><b>Implementation Considerations</b>
318 * <p>The exact operation of the {@link Condition} instance depends on
319 * the {@code Lock} implementation and must be documented by that
322 * @return A new {@link Condition} instance for this {@code Lock} instance
323 * @throws UnsupportedOperationException if this {@code Lock}
324 * implementation does not support conditions
326 Condition newCondition();