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