001 /*
002 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
003 *
004 * This code is free software; you can redistribute it and/or modify it
005 * under the terms of the GNU General Public License version 2 only, as
006 * published by the Free Software Foundation. Sun designates this
007 * particular file as subject to the "Classpath" exception as provided
008 * by Sun in the LICENSE file that accompanied this code.
009 *
010 * This code is distributed in the hope that it will be useful, but WITHOUT
011 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
012 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
013 * version 2 for more details (a copy is included in the LICENSE file that
014 * accompanied this code).
015 *
016 * You should have received a copy of the GNU General Public License version
017 * 2 along with this work; if not, write to the Free Software Foundation,
018 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
019 *
020 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
021 * CA 95054 USA or visit www.sun.com if you need additional information or
022 * have any questions.
023 */
024
025 /*
026 * This file is available under and governed by the GNU General Public
027 * License version 2 only, as published by the Free Software Foundation.
028 * However, the following notice accompanied the original version of this
029 * file:
030 *
031 * Written by Doug Lea with assistance from members of JCP JSR-166
032 * Expert Group and released to the public domain, as explained at
033 * http://creativecommons.org/licenses/publicdomain
034 */
035
036 package java.util.concurrent.locks;
037
038 import java.util.concurrent.TimeUnit;
039
040 /**
041 * {@code Lock} implementations provide more extensive locking
042 * operations than can be obtained using {@code synchronized} methods
043 * and statements. They allow more flexible structuring, may have
044 * quite different properties, and may support multiple associated
045 * {@link Condition} objects.
046 *
047 * <p>A lock is a tool for controlling access to a shared resource by
048 * multiple threads. Commonly, a lock provides exclusive access to a
049 * shared resource: only one thread at a time can acquire the lock and
050 * all access to the shared resource requires that the lock be
051 * acquired first. However, some locks may allow concurrent access to
052 * a shared resource, such as the read lock of a {@link ReadWriteLock}.
053 *
054 * <p>The use of {@code synchronized} methods or statements provides
055 * access to the implicit monitor lock associated with every object, but
056 * forces all lock acquisition and release to occur in a block-structured way:
057 * when multiple locks are acquired they must be released in the opposite
058 * order, and all locks must be released in the same lexical scope in which
059 * they were acquired.
060 *
061 * <p>While the scoping mechanism for {@code synchronized} methods
062 * and statements makes it much easier to program with monitor locks,
063 * and helps avoid many common programming errors involving locks,
064 * there are occasions where you need to work with locks in a more
065 * flexible way. For example, some algorithms for traversing
066 * concurrently accessed data structures require the use of
067 * "hand-over-hand" or "chain locking": you
068 * acquire the lock of node A, then node B, then release A and acquire
069 * C, then release B and acquire D and so on. Implementations of the
070 * {@code Lock} interface enable the use of such techniques by
071 * allowing a lock to be acquired and released in different scopes,
072 * and allowing multiple locks to be acquired and released in any
073 * order.
074 *
075 * <p>With this increased flexibility comes additional
076 * responsibility. The absence of block-structured locking removes the
077 * automatic release of locks that occurs with {@code synchronized}
078 * methods and statements. In most cases, the following idiom
079 * should be used:
080 *
081 * <pre><tt> Lock l = ...;
082 * l.lock();
083 * try {
084 * // access the resource protected by this lock
085 * } finally {
086 * l.unlock();
087 * }
088 * </tt></pre>
089 *
090 * When locking and unlocking occur in different scopes, care must be
091 * taken to ensure that all code that is executed while the lock is
092 * held is protected by try-finally or try-catch to ensure that the
093 * lock is released when necessary.
094 *
095 * <p>{@code Lock} implementations provide additional functionality
096 * over the use of {@code synchronized} methods and statements by
097 * providing a non-blocking attempt to acquire a lock ({@link
098 * #tryLock()}), an attempt to acquire the lock that can be
099 * interrupted ({@link #lockInterruptibly}, and an attempt to acquire
100 * the lock that can timeout ({@link #tryLock(long, TimeUnit)}).
101 *
102 * <p>A {@code Lock} class can also provide behavior and semantics
103 * that is quite different from that of the implicit monitor lock,
104 * such as guaranteed ordering, non-reentrant usage, or deadlock
105 * detection. If an implementation provides such specialized semantics
106 * then the implementation must document those semantics.
107 *
108 * <p>Note that {@code Lock} instances are just normal objects and can
109 * themselves be used as the target in a {@code synchronized} statement.
110 * Acquiring the
111 * monitor lock of a {@code Lock} instance has no specified relationship
112 * with invoking any of the {@link #lock} methods of that instance.
113 * It is recommended that to avoid confusion you never use {@code Lock}
114 * instances in this way, except within their own implementation.
115 *
116 * <p>Except where noted, passing a {@code null} value for any
117 * parameter will result in a {@link NullPointerException} being
118 * thrown.
119 *
120 * <h3>Memory Synchronization</h3>
121 *
122 * <p>All {@code Lock} implementations <em>must</em> enforce the same
123 * memory synchronization semantics as provided by the built-in monitor
124 * lock, as described in <a href="http://java.sun.com/docs/books/jls/">
125 * The Java Language Specification, Third Edition (17.4 Memory Model)</a>:
126 * <ul>
127 * <li>A successful {@code lock} operation has the same memory
128 * synchronization effects as a successful <em>Lock</em> action.
129 * <li>A successful {@code unlock} operation has the same
130 * memory synchronization effects as a successful <em>Unlock</em> action.
131 * </ul>
132 *
133 * Unsuccessful locking and unlocking operations, and reentrant
134 * locking/unlocking operations, do not require any memory
135 * synchronization effects.
136 *
137 * <h3>Implementation Considerations</h3>
138 *
139 * <p> The three forms of lock acquisition (interruptible,
140 * non-interruptible, and timed) may differ in their performance
141 * characteristics, ordering guarantees, or other implementation
142 * qualities. Further, the ability to interrupt the <em>ongoing</em>
143 * acquisition of a lock may not be available in a given {@code Lock}
144 * class. Consequently, an implementation is not required to define
145 * exactly the same guarantees or semantics for all three forms of
146 * lock acquisition, nor is it required to support interruption of an
147 * ongoing lock acquisition. An implementation is required to clearly
148 * document the semantics and guarantees provided by each of the
149 * locking methods. It must also obey the interruption semantics as
150 * defined in this interface, to the extent that interruption of lock
151 * acquisition is supported: which is either totally, or only on
152 * method entry.
153 *
154 * <p>As interruption generally implies cancellation, and checks for
155 * interruption are often infrequent, an implementation can favor responding
156 * to an interrupt over normal method return. This is true even if it can be
157 * shown that the interrupt occurred after another action may have unblocked
158 * the thread. An implementation should document this behavior.
159 *
160 * @see ReentrantLock
161 * @see Condition
162 * @see ReadWriteLock
163 *
164 * @since 1.5
165 * @author Doug Lea
166 */
167 public interface Lock {
168
169 /**
170 * Acquires the lock.
171 *
172 * <p>If the lock is not available then the current thread becomes
173 * disabled for thread scheduling purposes and lies dormant until the
174 * lock has been acquired.
175 *
176 * <p><b>Implementation Considerations</b>
177 *
178 * <p>A {@code Lock} implementation may be able to detect erroneous use
179 * of the lock, such as an invocation that would cause deadlock, and
180 * may throw an (unchecked) exception in such circumstances. The
181 * circumstances and the exception type must be documented by that
182 * {@code Lock} implementation.
183 */
184 void lock();
185
186 /**
187 * Acquires the lock unless the current thread is
188 * {@linkplain Thread#interrupt interrupted}.
189 *
190 * <p>Acquires the lock if it is available and returns immediately.
191 *
192 * <p>If the lock is not available then the current thread becomes
193 * disabled for thread scheduling purposes and lies dormant until
194 * one of two things happens:
195 *
196 * <ul>
197 * <li>The lock is acquired by the current thread; or
198 * <li>Some other thread {@linkplain Thread#interrupt interrupts} the
199 * current thread, and interruption of lock acquisition is supported.
200 * </ul>
201 *
202 * <p>If the current thread:
203 * <ul>
204 * <li>has its interrupted status set on entry to this method; or
205 * <li>is {@linkplain Thread#interrupt interrupted} while acquiring the
206 * lock, and interruption of lock acquisition is supported,
207 * </ul>
208 * then {@link InterruptedException} is thrown and the current thread's
209 * interrupted status is cleared.
210 *
211 * <p><b>Implementation Considerations</b>
212 *
213 * <p>The ability to interrupt a lock acquisition in some
214 * implementations may not be possible, and if possible may be an
215 * expensive operation. The programmer should be aware that this
216 * may be the case. An implementation should document when this is
217 * the case.
218 *
219 * <p>An implementation can favor responding to an interrupt over
220 * normal method return.
221 *
222 * <p>A {@code Lock} implementation may be able to detect
223 * erroneous use of the lock, such as an invocation that would
224 * cause deadlock, and may throw an (unchecked) exception in such
225 * circumstances. The circumstances and the exception type must
226 * be documented by that {@code Lock} implementation.
227 *
228 * @throws InterruptedException if the current thread is
229 * interrupted while acquiring the lock (and interruption
230 * of lock acquisition is supported).
231 */
232 void lockInterruptibly() throws InterruptedException;
233
234 /**
235 * Acquires the lock only if it is free at the time of invocation.
236 *
237 * <p>Acquires the lock if it is available and returns immediately
238 * with the value {@code true}.
239 * If the lock is not available then this method will return
240 * immediately with the value {@code false}.
241 *
242 * <p>A typical usage idiom for this method would be:
243 * <pre>
244 * Lock lock = ...;
245 * if (lock.tryLock()) {
246 * try {
247 * // manipulate protected state
248 * } finally {
249 * lock.unlock();
250 * }
251 * } else {
252 * // perform alternative actions
253 * }
254 * </pre>
255 * This usage ensures that the lock is unlocked if it was acquired, and
256 * doesn't try to unlock if the lock was not acquired.
257 *
258 * @return {@code true} if the lock was acquired and
259 * {@code false} otherwise
260 */
261 boolean tryLock();
262
263 /**
264 * Acquires the lock if it is free within the given waiting time and the
265 * current thread has not been {@linkplain Thread#interrupt interrupted}.
266 *
267 * <p>If the lock is available this method returns immediately
268 * with the value {@code true}.
269 * If the lock is not available then
270 * the current thread becomes disabled for thread scheduling
271 * purposes and lies dormant until one of three things happens:
272 * <ul>
273 * <li>The lock is acquired by the current thread; or
274 * <li>Some other thread {@linkplain Thread#interrupt interrupts} the
275 * current thread, and interruption of lock acquisition is supported; or
276 * <li>The specified waiting time elapses
277 * </ul>
278 *
279 * <p>If the lock is acquired then the value {@code true} is returned.
280 *
281 * <p>If the current thread:
282 * <ul>
283 * <li>has its interrupted status set on entry to this method; or
284 * <li>is {@linkplain Thread#interrupt interrupted} while acquiring
285 * the lock, and interruption of lock acquisition is supported,
286 * </ul>
287 * then {@link InterruptedException} is thrown and the current thread's
288 * interrupted status is cleared.
289 *
290 * <p>If the specified waiting time elapses then the value {@code false}
291 * is returned.
292 * If the time is
293 * less than or equal to zero, the method will not wait at all.
294 *
295 * <p><b>Implementation Considerations</b>
296 *
297 * <p>The ability to interrupt a lock acquisition in some implementations
298 * may not be possible, and if possible may
299 * be an expensive operation.
300 * The programmer should be aware that this may be the case. An
301 * implementation should document when this is the case.
302 *
303 * <p>An implementation can favor responding to an interrupt over normal
304 * method return, or reporting a timeout.
305 *
306 * <p>A {@code Lock} implementation may be able to detect
307 * erroneous use of the lock, such as an invocation that would cause
308 * deadlock, and may throw an (unchecked) exception in such circumstances.
309 * The circumstances and the exception type must be documented by that
310 * {@code Lock} implementation.
311 *
312 * @param time the maximum time to wait for the lock
313 * @param unit the time unit of the {@code time} argument
314 * @return {@code true} if the lock was acquired and {@code false}
315 * if the waiting time elapsed before the lock was acquired
316 *
317 * @throws InterruptedException if the current thread is interrupted
318 * while acquiring the lock (and interruption of lock
319 * acquisition is supported)
320 */
321 boolean tryLock(long time, TimeUnit unit)
322 throws InterruptedException;
323
324 /**
325 * Releases the lock.
326 *
327 * <p><b>Implementation Considerations</b>
328 *
329 * <p>A {@code Lock} implementation will usually impose
330 * restrictions on which thread can release a lock (typically only the
331 * holder of the lock can release it) and may throw
332 * an (unchecked) exception if the restriction is violated.
333 * Any restrictions and the exception
334 * type must be documented by that {@code Lock} implementation.
335 */
336 void unlock();
337
338 /**
339 * Returns a new {@link Condition} instance that is bound to this
340 * {@code Lock} instance.
341 *
342 * <p>Before waiting on the condition the lock must be held by the
343 * current thread.
344 * A call to {@link Condition#await()} will atomically release the lock
345 * before waiting and re-acquire the lock before the wait returns.
346 *
347 * <p><b>Implementation Considerations</b>
348 *
349 * <p>The exact operation of the {@link Condition} instance depends on
350 * the {@code Lock} implementation and must be documented by that
351 * implementation.
352 *
353 * @return A new {@link Condition} instance for this {@code Lock} instance
354 * @throws UnsupportedOperationException if this {@code Lock}
355 * implementation does not support conditions
356 */
357 Condition newCondition();
358 }
|