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 7 package java.util.concurrent.locks; 8 import java.util.concurrent.TimeUnit; 9 10 /** 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. 16 * 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}. 23 * 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 29 * they were acquired. 30 * 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 43 * order. 44 * 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 49 * should be used: 50 * 51 * <pre> {@code 52 * Lock l = ...; 53 * l.lock(); 54 * try { 55 * // access the resource protected by this lock 56 * } finally { 57 * l.unlock(); 58 * }}</pre> 59 * 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. 64 * 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)}). 71 * 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. 77 * 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. 80 * Acquiring the 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. 85 * 86 * <p>Except where noted, passing a {@code null} value for any 87 * parameter will result in a {@link NullPointerException} being 88 * thrown. 89 * 90 * <h3>Memory Synchronization</h3> 91 * 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 95 * <a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-17.html#jls-17.4"> 96 * The Java Language Specification (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 */ lock()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 */ lockInterruptibly()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> {@code 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 * }}</pre> 225 * 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 */ tryLock()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 */ tryLock(long time, TimeUnit unit)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 */ unlock()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 */ newCondition()327 Condition newCondition(); 328 } 329