1 /*
   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.  Oracle designates this
   7  * particular file as subject to the "Classpath" exception as provided
   8  * by Oracle 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  21  * or visit www.oracle.com if you need additional information or have any
  22  * 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/publicdomain/zero/1.0/
  34  */
  35 
  36 package java.util.concurrent.locks;
  37 import 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> {@code
  81  * Lock l = ...;
  82  * l.lock();
  83  * try {
  84  *   // access the resource protected by this lock
  85  * } finally {
  86  *   l.unlock();
  87  * }}</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
 124  * <a href="https://docs.oracle.com/javase/specs/jls/se7/html/jls-17.html#jls-17.4">
 125  * The Java Language Specification (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> {@code
 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      * }}</pre>
 254      *
 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) throws InterruptedException;
 322 
 323     /**
 324      * Releases the lock.
 325      *
 326      * <p><b>Implementation Considerations</b>
 327      *
 328      * <p>A {@code Lock} implementation will usually impose
 329      * restrictions on which thread can release a lock (typically only the
 330      * holder of the lock can release it) and may throw
 331      * an (unchecked) exception if the restriction is violated.
 332      * Any restrictions and the exception
 333      * type must be documented by that {@code Lock} implementation.
 334      */
 335     void unlock();
 336 
 337     /**
 338      * Returns a new {@link Condition} instance that is bound to this
 339      * {@code Lock} instance.
 340      *
 341      * <p>Before waiting on the condition the lock must be held by the
 342      * current thread.
 343      * A call to {@link Condition#await()} will atomically release the lock
 344      * before waiting and re-acquire the lock before the wait returns.
 345      *
 346      * <p><b>Implementation Considerations</b>
 347      *
 348      * <p>The exact operation of the {@link Condition} instance depends on
 349      * the {@code Lock} implementation and must be documented by that
 350      * implementation.
 351      *
 352      * @return A new {@link Condition} instance for this {@code Lock} instance
 353      * @throws UnsupportedOperationException if this {@code Lock}
 354      *         implementation does not support conditions
 355      */
 356     Condition newCondition();
 357 }