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