1/*
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/publicdomain/zero/1.0/
5 */
6
7package java.util.concurrent.locks;
8
9import 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> {@code
53 * Lock l = ...;
54 * l.lock();
55 * try {
56 *   // access the resource protected by this lock
57 * } finally {
58 *   l.unlock();
59 * }}</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
96 * <a href="https://docs.oracle.com/javase/specs/jls/se8/html/jls-17.html#jls-17.4">
97 * Chapter 17 of
98 * <cite>The Java&trade; Language Specification</cite></a>:
99 * <ul>
100 * <li>A successful {@code lock} operation has the same memory
101 * synchronization effects as a successful <em>Lock</em> action.
102 * <li>A successful {@code unlock} operation has the same
103 * memory synchronization effects as a successful <em>Unlock</em> action.
104 * </ul>
105 *
106 * Unsuccessful locking and unlocking operations, and reentrant
107 * locking/unlocking operations, do not require any memory
108 * synchronization effects.
109 *
110 * <h3>Implementation Considerations</h3>
111 *
112 * <p>The three forms of lock acquisition (interruptible,
113 * non-interruptible, and timed) may differ in their performance
114 * characteristics, ordering guarantees, or other implementation
115 * qualities.  Further, the ability to interrupt the <em>ongoing</em>
116 * acquisition of a lock may not be available in a given {@code Lock}
117 * class.  Consequently, an implementation is not required to define
118 * exactly the same guarantees or semantics for all three forms of
119 * lock acquisition, nor is it required to support interruption of an
120 * ongoing lock acquisition.  An implementation is required to clearly
121 * document the semantics and guarantees provided by each of the
122 * locking methods. It must also obey the interruption semantics as
123 * defined in this interface, to the extent that interruption of lock
124 * acquisition is supported: which is either totally, or only on
125 * method entry.
126 *
127 * <p>As interruption generally implies cancellation, and checks for
128 * interruption are often infrequent, an implementation can favor responding
129 * to an interrupt over normal method return. This is true even if it can be
130 * shown that the interrupt occurred after another action may have unblocked
131 * the thread. An implementation should document this behavior.
132 *
133 * @see ReentrantLock
134 * @see Condition
135 * @see ReadWriteLock
136 *
137 * @since 1.5
138 * @author Doug Lea
139 */
140public interface Lock {
141
142    /**
143     * Acquires the lock.
144     *
145     * <p>If the lock is not available then the current thread becomes
146     * disabled for thread scheduling purposes and lies dormant until the
147     * lock has been acquired.
148     *
149     * <p><b>Implementation Considerations</b>
150     *
151     * <p>A {@code Lock} implementation may be able to detect erroneous use
152     * of the lock, such as an invocation that would cause deadlock, and
153     * may throw an (unchecked) exception in such circumstances.  The
154     * circumstances and the exception type must be documented by that
155     * {@code Lock} implementation.
156     */
157    void lock();
158
159    /**
160     * Acquires the lock unless the current thread is
161     * {@linkplain Thread#interrupt interrupted}.
162     *
163     * <p>Acquires the lock if it is available and returns immediately.
164     *
165     * <p>If the lock is not available then the current thread becomes
166     * disabled for thread scheduling purposes and lies dormant until
167     * one of two things happens:
168     *
169     * <ul>
170     * <li>The lock is acquired by the current thread; or
171     * <li>Some other thread {@linkplain Thread#interrupt interrupts} the
172     * current thread, and interruption of lock acquisition is supported.
173     * </ul>
174     *
175     * <p>If the current thread:
176     * <ul>
177     * <li>has its interrupted status set on entry to this method; or
178     * <li>is {@linkplain Thread#interrupt interrupted} while acquiring the
179     * lock, and interruption of lock acquisition is supported,
180     * </ul>
181     * then {@link InterruptedException} is thrown and the current thread's
182     * interrupted status is cleared.
183     *
184     * <p><b>Implementation Considerations</b>
185     *
186     * <p>The ability to interrupt a lock acquisition in some
187     * implementations may not be possible, and if possible may be an
188     * expensive operation.  The programmer should be aware that this
189     * may be the case. An implementation should document when this is
190     * the case.
191     *
192     * <p>An implementation can favor responding to an interrupt over
193     * normal method return.
194     *
195     * <p>A {@code Lock} implementation may be able to detect
196     * erroneous use of the lock, such as an invocation that would
197     * cause deadlock, and may throw an (unchecked) exception in such
198     * circumstances.  The circumstances and the exception type must
199     * be documented by that {@code Lock} implementation.
200     *
201     * @throws InterruptedException if the current thread is
202     *         interrupted while acquiring the lock (and interruption
203     *         of lock acquisition is supported)
204     */
205    void lockInterruptibly() throws InterruptedException;
206
207    /**
208     * Acquires the lock only if it is free at the time of invocation.
209     *
210     * <p>Acquires the lock if it is available and returns immediately
211     * with the value {@code true}.
212     * If the lock is not available then this method will return
213     * immediately with the value {@code false}.
214     *
215     * <p>A typical usage idiom for this method would be:
216     * <pre> {@code
217     * Lock lock = ...;
218     * if (lock.tryLock()) {
219     *   try {
220     *     // manipulate protected state
221     *   } finally {
222     *     lock.unlock();
223     *   }
224     * } else {
225     *   // perform alternative actions
226     * }}</pre>
227     *
228     * This usage ensures that the lock is unlocked if it was acquired, and
229     * doesn't try to unlock if the lock was not acquired.
230     *
231     * @return {@code true} if the lock was acquired and
232     *         {@code false} otherwise
233     */
234    boolean tryLock();
235
236    /**
237     * Acquires the lock if it is free within the given waiting time and the
238     * current thread has not been {@linkplain Thread#interrupt interrupted}.
239     *
240     * <p>If the lock is available this method returns immediately
241     * with the value {@code true}.
242     * If the lock is not available then
243     * the current thread becomes disabled for thread scheduling
244     * purposes and lies dormant until one of three things happens:
245     * <ul>
246     * <li>The lock is acquired by the current thread; or
247     * <li>Some other thread {@linkplain Thread#interrupt interrupts} the
248     * current thread, and interruption of lock acquisition is supported; or
249     * <li>The specified waiting time elapses
250     * </ul>
251     *
252     * <p>If the lock is acquired then the value {@code true} is returned.
253     *
254     * <p>If the current thread:
255     * <ul>
256     * <li>has its interrupted status set on entry to this method; or
257     * <li>is {@linkplain Thread#interrupt interrupted} while acquiring
258     * the lock, and interruption of lock acquisition is supported,
259     * </ul>
260     * then {@link InterruptedException} is thrown and the current thread's
261     * interrupted status is cleared.
262     *
263     * <p>If the specified waiting time elapses then the value {@code false}
264     * is returned.
265     * If the time is
266     * less than or equal to zero, the method will not wait at all.
267     *
268     * <p><b>Implementation Considerations</b>
269     *
270     * <p>The ability to interrupt a lock acquisition in some implementations
271     * may not be possible, and if possible may
272     * be an expensive operation.
273     * The programmer should be aware that this may be the case. An
274     * implementation should document when this is the case.
275     *
276     * <p>An implementation can favor responding to an interrupt over normal
277     * method return, or reporting a timeout.
278     *
279     * <p>A {@code Lock} implementation may be able to detect
280     * erroneous use of the lock, such as an invocation that would cause
281     * deadlock, and may throw an (unchecked) exception in such circumstances.
282     * The circumstances and the exception type must be documented by that
283     * {@code Lock} implementation.
284     *
285     * @param time the maximum time to wait for the lock
286     * @param unit the time unit of the {@code time} argument
287     * @return {@code true} if the lock was acquired and {@code false}
288     *         if the waiting time elapsed before the lock was acquired
289     *
290     * @throws InterruptedException if the current thread is interrupted
291     *         while acquiring the lock (and interruption of lock
292     *         acquisition is supported)
293     */
294    boolean tryLock(long time, TimeUnit unit) throws InterruptedException;
295
296    /**
297     * Releases the lock.
298     *
299     * <p><b>Implementation Considerations</b>
300     *
301     * <p>A {@code Lock} implementation will usually impose
302     * restrictions on which thread can release a lock (typically only the
303     * holder of the lock can release it) and may throw
304     * an (unchecked) exception if the restriction is violated.
305     * Any restrictions and the exception
306     * type must be documented by that {@code Lock} implementation.
307     */
308    void unlock();
309
310    /**
311     * Returns a new {@link Condition} instance that is bound to this
312     * {@code Lock} instance.
313     *
314     * <p>Before waiting on the condition the lock must be held by the
315     * current thread.
316     * A call to {@link Condition#await()} will atomically release the lock
317     * before waiting and re-acquire the lock before the wait returns.
318     *
319     * <p><b>Implementation Considerations</b>
320     *
321     * <p>The exact operation of the {@link Condition} instance depends on
322     * the {@code Lock} implementation and must be documented by that
323     * implementation.
324     *
325     * @return A new {@link Condition} instance for this {@code Lock} instance
326     * @throws UnsupportedOperationException if this {@code Lock}
327     *         implementation does not support conditions
328     */
329    Condition newCondition();
330}
331