rt/emul/compact/src/main/java/java/util/concurrent/locks/ReentrantLock.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Sat, 19 Mar 2016 10:46:31 +0100
branchjdk7-b147
changeset 1890 212417b74b72
permissions -rw-r--r--
Bringing in all concurrent package from JDK7-b147
jaroslav@1890
     1
/*
jaroslav@1890
     2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
jaroslav@1890
     3
 *
jaroslav@1890
     4
 * This code is free software; you can redistribute it and/or modify it
jaroslav@1890
     5
 * under the terms of the GNU General Public License version 2 only, as
jaroslav@1890
     6
 * published by the Free Software Foundation.  Oracle designates this
jaroslav@1890
     7
 * particular file as subject to the "Classpath" exception as provided
jaroslav@1890
     8
 * by Oracle in the LICENSE file that accompanied this code.
jaroslav@1890
     9
 *
jaroslav@1890
    10
 * This code is distributed in the hope that it will be useful, but WITHOUT
jaroslav@1890
    11
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
jaroslav@1890
    12
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
jaroslav@1890
    13
 * version 2 for more details (a copy is included in the LICENSE file that
jaroslav@1890
    14
 * accompanied this code).
jaroslav@1890
    15
 *
jaroslav@1890
    16
 * You should have received a copy of the GNU General Public License version
jaroslav@1890
    17
 * 2 along with this work; if not, write to the Free Software Foundation,
jaroslav@1890
    18
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
jaroslav@1890
    19
 *
jaroslav@1890
    20
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
jaroslav@1890
    21
 * or visit www.oracle.com if you need additional information or have any
jaroslav@1890
    22
 * questions.
jaroslav@1890
    23
 */
jaroslav@1890
    24
jaroslav@1890
    25
/*
jaroslav@1890
    26
 * This file is available under and governed by the GNU General Public
jaroslav@1890
    27
 * License version 2 only, as published by the Free Software Foundation.
jaroslav@1890
    28
 * However, the following notice accompanied the original version of this
jaroslav@1890
    29
 * file:
jaroslav@1890
    30
 *
jaroslav@1890
    31
 * Written by Doug Lea with assistance from members of JCP JSR-166
jaroslav@1890
    32
 * Expert Group and released to the public domain, as explained at
jaroslav@1890
    33
 * http://creativecommons.org/publicdomain/zero/1.0/
jaroslav@1890
    34
 */
jaroslav@1890
    35
jaroslav@1890
    36
package java.util.concurrent.locks;
jaroslav@1890
    37
import java.util.*;
jaroslav@1890
    38
import java.util.concurrent.*;
jaroslav@1890
    39
import java.util.concurrent.atomic.*;
jaroslav@1890
    40
jaroslav@1890
    41
/**
jaroslav@1890
    42
 * A reentrant mutual exclusion {@link Lock} with the same basic
jaroslav@1890
    43
 * behavior and semantics as the implicit monitor lock accessed using
jaroslav@1890
    44
 * {@code synchronized} methods and statements, but with extended
jaroslav@1890
    45
 * capabilities.
jaroslav@1890
    46
 *
jaroslav@1890
    47
 * <p>A {@code ReentrantLock} is <em>owned</em> by the thread last
jaroslav@1890
    48
 * successfully locking, but not yet unlocking it. A thread invoking
jaroslav@1890
    49
 * {@code lock} will return, successfully acquiring the lock, when
jaroslav@1890
    50
 * the lock is not owned by another thread. The method will return
jaroslav@1890
    51
 * immediately if the current thread already owns the lock. This can
jaroslav@1890
    52
 * be checked using methods {@link #isHeldByCurrentThread}, and {@link
jaroslav@1890
    53
 * #getHoldCount}.
jaroslav@1890
    54
 *
jaroslav@1890
    55
 * <p>The constructor for this class accepts an optional
jaroslav@1890
    56
 * <em>fairness</em> parameter.  When set {@code true}, under
jaroslav@1890
    57
 * contention, locks favor granting access to the longest-waiting
jaroslav@1890
    58
 * thread.  Otherwise this lock does not guarantee any particular
jaroslav@1890
    59
 * access order.  Programs using fair locks accessed by many threads
jaroslav@1890
    60
 * may display lower overall throughput (i.e., are slower; often much
jaroslav@1890
    61
 * slower) than those using the default setting, but have smaller
jaroslav@1890
    62
 * variances in times to obtain locks and guarantee lack of
jaroslav@1890
    63
 * starvation. Note however, that fairness of locks does not guarantee
jaroslav@1890
    64
 * fairness of thread scheduling. Thus, one of many threads using a
jaroslav@1890
    65
 * fair lock may obtain it multiple times in succession while other
jaroslav@1890
    66
 * active threads are not progressing and not currently holding the
jaroslav@1890
    67
 * lock.
jaroslav@1890
    68
 * Also note that the untimed {@link #tryLock() tryLock} method does not
jaroslav@1890
    69
 * honor the fairness setting. It will succeed if the lock
jaroslav@1890
    70
 * is available even if other threads are waiting.
jaroslav@1890
    71
 *
jaroslav@1890
    72
 * <p>It is recommended practice to <em>always</em> immediately
jaroslav@1890
    73
 * follow a call to {@code lock} with a {@code try} block, most
jaroslav@1890
    74
 * typically in a before/after construction such as:
jaroslav@1890
    75
 *
jaroslav@1890
    76
 * <pre>
jaroslav@1890
    77
 * class X {
jaroslav@1890
    78
 *   private final ReentrantLock lock = new ReentrantLock();
jaroslav@1890
    79
 *   // ...
jaroslav@1890
    80
 *
jaroslav@1890
    81
 *   public void m() {
jaroslav@1890
    82
 *     lock.lock();  // block until condition holds
jaroslav@1890
    83
 *     try {
jaroslav@1890
    84
 *       // ... method body
jaroslav@1890
    85
 *     } finally {
jaroslav@1890
    86
 *       lock.unlock()
jaroslav@1890
    87
 *     }
jaroslav@1890
    88
 *   }
jaroslav@1890
    89
 * }
jaroslav@1890
    90
 * </pre>
jaroslav@1890
    91
 *
jaroslav@1890
    92
 * <p>In addition to implementing the {@link Lock} interface, this
jaroslav@1890
    93
 * class defines methods {@code isLocked} and
jaroslav@1890
    94
 * {@code getLockQueueLength}, as well as some associated
jaroslav@1890
    95
 * {@code protected} access methods that may be useful for
jaroslav@1890
    96
 * instrumentation and monitoring.
jaroslav@1890
    97
 *
jaroslav@1890
    98
 * <p>Serialization of this class behaves in the same way as built-in
jaroslav@1890
    99
 * locks: a deserialized lock is in the unlocked state, regardless of
jaroslav@1890
   100
 * its state when serialized.
jaroslav@1890
   101
 *
jaroslav@1890
   102
 * <p>This lock supports a maximum of 2147483647 recursive locks by
jaroslav@1890
   103
 * the same thread. Attempts to exceed this limit result in
jaroslav@1890
   104
 * {@link Error} throws from locking methods.
jaroslav@1890
   105
 *
jaroslav@1890
   106
 * @since 1.5
jaroslav@1890
   107
 * @author Doug Lea
jaroslav@1890
   108
 */
jaroslav@1890
   109
public class ReentrantLock implements Lock, java.io.Serializable {
jaroslav@1890
   110
    private static final long serialVersionUID = 7373984872572414699L;
jaroslav@1890
   111
    /** Synchronizer providing all implementation mechanics */
jaroslav@1890
   112
    private final Sync sync;
jaroslav@1890
   113
jaroslav@1890
   114
    /**
jaroslav@1890
   115
     * Base of synchronization control for this lock. Subclassed
jaroslav@1890
   116
     * into fair and nonfair versions below. Uses AQS state to
jaroslav@1890
   117
     * represent the number of holds on the lock.
jaroslav@1890
   118
     */
jaroslav@1890
   119
    abstract static class Sync extends AbstractQueuedSynchronizer {
jaroslav@1890
   120
        private static final long serialVersionUID = -5179523762034025860L;
jaroslav@1890
   121
jaroslav@1890
   122
        /**
jaroslav@1890
   123
         * Performs {@link Lock#lock}. The main reason for subclassing
jaroslav@1890
   124
         * is to allow fast path for nonfair version.
jaroslav@1890
   125
         */
jaroslav@1890
   126
        abstract void lock();
jaroslav@1890
   127
jaroslav@1890
   128
        /**
jaroslav@1890
   129
         * Performs non-fair tryLock.  tryAcquire is
jaroslav@1890
   130
         * implemented in subclasses, but both need nonfair
jaroslav@1890
   131
         * try for trylock method.
jaroslav@1890
   132
         */
jaroslav@1890
   133
        final boolean nonfairTryAcquire(int acquires) {
jaroslav@1890
   134
            final Thread current = Thread.currentThread();
jaroslav@1890
   135
            int c = getState();
jaroslav@1890
   136
            if (c == 0) {
jaroslav@1890
   137
                if (compareAndSetState(0, acquires)) {
jaroslav@1890
   138
                    setExclusiveOwnerThread(current);
jaroslav@1890
   139
                    return true;
jaroslav@1890
   140
                }
jaroslav@1890
   141
            }
jaroslav@1890
   142
            else if (current == getExclusiveOwnerThread()) {
jaroslav@1890
   143
                int nextc = c + acquires;
jaroslav@1890
   144
                if (nextc < 0) // overflow
jaroslav@1890
   145
                    throw new Error("Maximum lock count exceeded");
jaroslav@1890
   146
                setState(nextc);
jaroslav@1890
   147
                return true;
jaroslav@1890
   148
            }
jaroslav@1890
   149
            return false;
jaroslav@1890
   150
        }
jaroslav@1890
   151
jaroslav@1890
   152
        protected final boolean tryRelease(int releases) {
jaroslav@1890
   153
            int c = getState() - releases;
jaroslav@1890
   154
            if (Thread.currentThread() != getExclusiveOwnerThread())
jaroslav@1890
   155
                throw new IllegalMonitorStateException();
jaroslav@1890
   156
            boolean free = false;
jaroslav@1890
   157
            if (c == 0) {
jaroslav@1890
   158
                free = true;
jaroslav@1890
   159
                setExclusiveOwnerThread(null);
jaroslav@1890
   160
            }
jaroslav@1890
   161
            setState(c);
jaroslav@1890
   162
            return free;
jaroslav@1890
   163
        }
jaroslav@1890
   164
jaroslav@1890
   165
        protected final boolean isHeldExclusively() {
jaroslav@1890
   166
            // While we must in general read state before owner,
jaroslav@1890
   167
            // we don't need to do so to check if current thread is owner
jaroslav@1890
   168
            return getExclusiveOwnerThread() == Thread.currentThread();
jaroslav@1890
   169
        }
jaroslav@1890
   170
jaroslav@1890
   171
        final ConditionObject newCondition() {
jaroslav@1890
   172
            return new ConditionObject();
jaroslav@1890
   173
        }
jaroslav@1890
   174
jaroslav@1890
   175
        // Methods relayed from outer class
jaroslav@1890
   176
jaroslav@1890
   177
        final Thread getOwner() {
jaroslav@1890
   178
            return getState() == 0 ? null : getExclusiveOwnerThread();
jaroslav@1890
   179
        }
jaroslav@1890
   180
jaroslav@1890
   181
        final int getHoldCount() {
jaroslav@1890
   182
            return isHeldExclusively() ? getState() : 0;
jaroslav@1890
   183
        }
jaroslav@1890
   184
jaroslav@1890
   185
        final boolean isLocked() {
jaroslav@1890
   186
            return getState() != 0;
jaroslav@1890
   187
        }
jaroslav@1890
   188
jaroslav@1890
   189
        /**
jaroslav@1890
   190
         * Reconstitutes this lock instance from a stream.
jaroslav@1890
   191
         * @param s the stream
jaroslav@1890
   192
         */
jaroslav@1890
   193
        private void readObject(java.io.ObjectInputStream s)
jaroslav@1890
   194
            throws java.io.IOException, ClassNotFoundException {
jaroslav@1890
   195
            s.defaultReadObject();
jaroslav@1890
   196
            setState(0); // reset to unlocked state
jaroslav@1890
   197
        }
jaroslav@1890
   198
    }
jaroslav@1890
   199
jaroslav@1890
   200
    /**
jaroslav@1890
   201
     * Sync object for non-fair locks
jaroslav@1890
   202
     */
jaroslav@1890
   203
    static final class NonfairSync extends Sync {
jaroslav@1890
   204
        private static final long serialVersionUID = 7316153563782823691L;
jaroslav@1890
   205
jaroslav@1890
   206
        /**
jaroslav@1890
   207
         * Performs lock.  Try immediate barge, backing up to normal
jaroslav@1890
   208
         * acquire on failure.
jaroslav@1890
   209
         */
jaroslav@1890
   210
        final void lock() {
jaroslav@1890
   211
            if (compareAndSetState(0, 1))
jaroslav@1890
   212
                setExclusiveOwnerThread(Thread.currentThread());
jaroslav@1890
   213
            else
jaroslav@1890
   214
                acquire(1);
jaroslav@1890
   215
        }
jaroslav@1890
   216
jaroslav@1890
   217
        protected final boolean tryAcquire(int acquires) {
jaroslav@1890
   218
            return nonfairTryAcquire(acquires);
jaroslav@1890
   219
        }
jaroslav@1890
   220
    }
jaroslav@1890
   221
jaroslav@1890
   222
    /**
jaroslav@1890
   223
     * Sync object for fair locks
jaroslav@1890
   224
     */
jaroslav@1890
   225
    static final class FairSync extends Sync {
jaroslav@1890
   226
        private static final long serialVersionUID = -3000897897090466540L;
jaroslav@1890
   227
jaroslav@1890
   228
        final void lock() {
jaroslav@1890
   229
            acquire(1);
jaroslav@1890
   230
        }
jaroslav@1890
   231
jaroslav@1890
   232
        /**
jaroslav@1890
   233
         * Fair version of tryAcquire.  Don't grant access unless
jaroslav@1890
   234
         * recursive call or no waiters or is first.
jaroslav@1890
   235
         */
jaroslav@1890
   236
        protected final boolean tryAcquire(int acquires) {
jaroslav@1890
   237
            final Thread current = Thread.currentThread();
jaroslav@1890
   238
            int c = getState();
jaroslav@1890
   239
            if (c == 0) {
jaroslav@1890
   240
                if (!hasQueuedPredecessors() &&
jaroslav@1890
   241
                    compareAndSetState(0, acquires)) {
jaroslav@1890
   242
                    setExclusiveOwnerThread(current);
jaroslav@1890
   243
                    return true;
jaroslav@1890
   244
                }
jaroslav@1890
   245
            }
jaroslav@1890
   246
            else if (current == getExclusiveOwnerThread()) {
jaroslav@1890
   247
                int nextc = c + acquires;
jaroslav@1890
   248
                if (nextc < 0)
jaroslav@1890
   249
                    throw new Error("Maximum lock count exceeded");
jaroslav@1890
   250
                setState(nextc);
jaroslav@1890
   251
                return true;
jaroslav@1890
   252
            }
jaroslav@1890
   253
            return false;
jaroslav@1890
   254
        }
jaroslav@1890
   255
    }
jaroslav@1890
   256
jaroslav@1890
   257
    /**
jaroslav@1890
   258
     * Creates an instance of {@code ReentrantLock}.
jaroslav@1890
   259
     * This is equivalent to using {@code ReentrantLock(false)}.
jaroslav@1890
   260
     */
jaroslav@1890
   261
    public ReentrantLock() {
jaroslav@1890
   262
        sync = new NonfairSync();
jaroslav@1890
   263
    }
jaroslav@1890
   264
jaroslav@1890
   265
    /**
jaroslav@1890
   266
     * Creates an instance of {@code ReentrantLock} with the
jaroslav@1890
   267
     * given fairness policy.
jaroslav@1890
   268
     *
jaroslav@1890
   269
     * @param fair {@code true} if this lock should use a fair ordering policy
jaroslav@1890
   270
     */
jaroslav@1890
   271
    public ReentrantLock(boolean fair) {
jaroslav@1890
   272
        sync = fair ? new FairSync() : new NonfairSync();
jaroslav@1890
   273
    }
jaroslav@1890
   274
jaroslav@1890
   275
    /**
jaroslav@1890
   276
     * Acquires the lock.
jaroslav@1890
   277
     *
jaroslav@1890
   278
     * <p>Acquires the lock if it is not held by another thread and returns
jaroslav@1890
   279
     * immediately, setting the lock hold count to one.
jaroslav@1890
   280
     *
jaroslav@1890
   281
     * <p>If the current thread already holds the lock then the hold
jaroslav@1890
   282
     * count is incremented by one and the method returns immediately.
jaroslav@1890
   283
     *
jaroslav@1890
   284
     * <p>If the lock is held by another thread then the
jaroslav@1890
   285
     * current thread becomes disabled for thread scheduling
jaroslav@1890
   286
     * purposes and lies dormant until the lock has been acquired,
jaroslav@1890
   287
     * at which time the lock hold count is set to one.
jaroslav@1890
   288
     */
jaroslav@1890
   289
    public void lock() {
jaroslav@1890
   290
        sync.lock();
jaroslav@1890
   291
    }
jaroslav@1890
   292
jaroslav@1890
   293
    /**
jaroslav@1890
   294
     * Acquires the lock unless the current thread is
jaroslav@1890
   295
     * {@linkplain Thread#interrupt interrupted}.
jaroslav@1890
   296
     *
jaroslav@1890
   297
     * <p>Acquires the lock if it is not held by another thread and returns
jaroslav@1890
   298
     * immediately, setting the lock hold count to one.
jaroslav@1890
   299
     *
jaroslav@1890
   300
     * <p>If the current thread already holds this lock then the hold count
jaroslav@1890
   301
     * is incremented by one and the method returns immediately.
jaroslav@1890
   302
     *
jaroslav@1890
   303
     * <p>If the lock is held by another thread then the
jaroslav@1890
   304
     * current thread becomes disabled for thread scheduling
jaroslav@1890
   305
     * purposes and lies dormant until one of two things happens:
jaroslav@1890
   306
     *
jaroslav@1890
   307
     * <ul>
jaroslav@1890
   308
     *
jaroslav@1890
   309
     * <li>The lock is acquired by the current thread; or
jaroslav@1890
   310
     *
jaroslav@1890
   311
     * <li>Some other thread {@linkplain Thread#interrupt interrupts} the
jaroslav@1890
   312
     * current thread.
jaroslav@1890
   313
     *
jaroslav@1890
   314
     * </ul>
jaroslav@1890
   315
     *
jaroslav@1890
   316
     * <p>If the lock is acquired by the current thread then the lock hold
jaroslav@1890
   317
     * count is set to one.
jaroslav@1890
   318
     *
jaroslav@1890
   319
     * <p>If the current thread:
jaroslav@1890
   320
     *
jaroslav@1890
   321
     * <ul>
jaroslav@1890
   322
     *
jaroslav@1890
   323
     * <li>has its interrupted status set on entry to this method; or
jaroslav@1890
   324
     *
jaroslav@1890
   325
     * <li>is {@linkplain Thread#interrupt interrupted} while acquiring
jaroslav@1890
   326
     * the lock,
jaroslav@1890
   327
     *
jaroslav@1890
   328
     * </ul>
jaroslav@1890
   329
     *
jaroslav@1890
   330
     * then {@link InterruptedException} is thrown and the current thread's
jaroslav@1890
   331
     * interrupted status is cleared.
jaroslav@1890
   332
     *
jaroslav@1890
   333
     * <p>In this implementation, as this method is an explicit
jaroslav@1890
   334
     * interruption point, preference is given to responding to the
jaroslav@1890
   335
     * interrupt over normal or reentrant acquisition of the lock.
jaroslav@1890
   336
     *
jaroslav@1890
   337
     * @throws InterruptedException if the current thread is interrupted
jaroslav@1890
   338
     */
jaroslav@1890
   339
    public void lockInterruptibly() throws InterruptedException {
jaroslav@1890
   340
        sync.acquireInterruptibly(1);
jaroslav@1890
   341
    }
jaroslav@1890
   342
jaroslav@1890
   343
    /**
jaroslav@1890
   344
     * Acquires the lock only if it is not held by another thread at the time
jaroslav@1890
   345
     * of invocation.
jaroslav@1890
   346
     *
jaroslav@1890
   347
     * <p>Acquires the lock if it is not held by another thread and
jaroslav@1890
   348
     * returns immediately with the value {@code true}, setting the
jaroslav@1890
   349
     * lock hold count to one. Even when this lock has been set to use a
jaroslav@1890
   350
     * fair ordering policy, a call to {@code tryLock()} <em>will</em>
jaroslav@1890
   351
     * immediately acquire the lock if it is available, whether or not
jaroslav@1890
   352
     * other threads are currently waiting for the lock.
jaroslav@1890
   353
     * This &quot;barging&quot; behavior can be useful in certain
jaroslav@1890
   354
     * circumstances, even though it breaks fairness. If you want to honor
jaroslav@1890
   355
     * the fairness setting for this lock, then use
jaroslav@1890
   356
     * {@link #tryLock(long, TimeUnit) tryLock(0, TimeUnit.SECONDS) }
jaroslav@1890
   357
     * which is almost equivalent (it also detects interruption).
jaroslav@1890
   358
     *
jaroslav@1890
   359
     * <p> If the current thread already holds this lock then the hold
jaroslav@1890
   360
     * count is incremented by one and the method returns {@code true}.
jaroslav@1890
   361
     *
jaroslav@1890
   362
     * <p>If the lock is held by another thread then this method will return
jaroslav@1890
   363
     * immediately with the value {@code false}.
jaroslav@1890
   364
     *
jaroslav@1890
   365
     * @return {@code true} if the lock was free and was acquired by the
jaroslav@1890
   366
     *         current thread, or the lock was already held by the current
jaroslav@1890
   367
     *         thread; and {@code false} otherwise
jaroslav@1890
   368
     */
jaroslav@1890
   369
    public boolean tryLock() {
jaroslav@1890
   370
        return sync.nonfairTryAcquire(1);
jaroslav@1890
   371
    }
jaroslav@1890
   372
jaroslav@1890
   373
    /**
jaroslav@1890
   374
     * Acquires the lock if it is not held by another thread within the given
jaroslav@1890
   375
     * waiting time and the current thread has not been
jaroslav@1890
   376
     * {@linkplain Thread#interrupt interrupted}.
jaroslav@1890
   377
     *
jaroslav@1890
   378
     * <p>Acquires the lock if it is not held by another thread and returns
jaroslav@1890
   379
     * immediately with the value {@code true}, setting the lock hold count
jaroslav@1890
   380
     * to one. If this lock has been set to use a fair ordering policy then
jaroslav@1890
   381
     * an available lock <em>will not</em> be acquired if any other threads
jaroslav@1890
   382
     * are waiting for the lock. This is in contrast to the {@link #tryLock()}
jaroslav@1890
   383
     * method. If you want a timed {@code tryLock} that does permit barging on
jaroslav@1890
   384
     * a fair lock then combine the timed and un-timed forms together:
jaroslav@1890
   385
     *
jaroslav@1890
   386
     * <pre>if (lock.tryLock() || lock.tryLock(timeout, unit) ) { ... }
jaroslav@1890
   387
     * </pre>
jaroslav@1890
   388
     *
jaroslav@1890
   389
     * <p>If the current thread
jaroslav@1890
   390
     * already holds this lock then the hold count is incremented by one and
jaroslav@1890
   391
     * the method returns {@code true}.
jaroslav@1890
   392
     *
jaroslav@1890
   393
     * <p>If the lock is held by another thread then the
jaroslav@1890
   394
     * current thread becomes disabled for thread scheduling
jaroslav@1890
   395
     * purposes and lies dormant until one of three things happens:
jaroslav@1890
   396
     *
jaroslav@1890
   397
     * <ul>
jaroslav@1890
   398
     *
jaroslav@1890
   399
     * <li>The lock is acquired by the current thread; or
jaroslav@1890
   400
     *
jaroslav@1890
   401
     * <li>Some other thread {@linkplain Thread#interrupt interrupts}
jaroslav@1890
   402
     * the current thread; or
jaroslav@1890
   403
     *
jaroslav@1890
   404
     * <li>The specified waiting time elapses
jaroslav@1890
   405
     *
jaroslav@1890
   406
     * </ul>
jaroslav@1890
   407
     *
jaroslav@1890
   408
     * <p>If the lock is acquired then the value {@code true} is returned and
jaroslav@1890
   409
     * the lock hold count is set to one.
jaroslav@1890
   410
     *
jaroslav@1890
   411
     * <p>If the current thread:
jaroslav@1890
   412
     *
jaroslav@1890
   413
     * <ul>
jaroslav@1890
   414
     *
jaroslav@1890
   415
     * <li>has its interrupted status set on entry to this method; or
jaroslav@1890
   416
     *
jaroslav@1890
   417
     * <li>is {@linkplain Thread#interrupt interrupted} while
jaroslav@1890
   418
     * acquiring the lock,
jaroslav@1890
   419
     *
jaroslav@1890
   420
     * </ul>
jaroslav@1890
   421
     * then {@link InterruptedException} is thrown and the current thread's
jaroslav@1890
   422
     * interrupted status is cleared.
jaroslav@1890
   423
     *
jaroslav@1890
   424
     * <p>If the specified waiting time elapses then the value {@code false}
jaroslav@1890
   425
     * is returned.  If the time is less than or equal to zero, the method
jaroslav@1890
   426
     * will not wait at all.
jaroslav@1890
   427
     *
jaroslav@1890
   428
     * <p>In this implementation, as this method is an explicit
jaroslav@1890
   429
     * interruption point, preference is given to responding to the
jaroslav@1890
   430
     * interrupt over normal or reentrant acquisition of the lock, and
jaroslav@1890
   431
     * over reporting the elapse of the waiting time.
jaroslav@1890
   432
     *
jaroslav@1890
   433
     * @param timeout the time to wait for the lock
jaroslav@1890
   434
     * @param unit the time unit of the timeout argument
jaroslav@1890
   435
     * @return {@code true} if the lock was free and was acquired by the
jaroslav@1890
   436
     *         current thread, or the lock was already held by the current
jaroslav@1890
   437
     *         thread; and {@code false} if the waiting time elapsed before
jaroslav@1890
   438
     *         the lock could be acquired
jaroslav@1890
   439
     * @throws InterruptedException if the current thread is interrupted
jaroslav@1890
   440
     * @throws NullPointerException if the time unit is null
jaroslav@1890
   441
     *
jaroslav@1890
   442
     */
jaroslav@1890
   443
    public boolean tryLock(long timeout, TimeUnit unit)
jaroslav@1890
   444
            throws InterruptedException {
jaroslav@1890
   445
        return sync.tryAcquireNanos(1, unit.toNanos(timeout));
jaroslav@1890
   446
    }
jaroslav@1890
   447
jaroslav@1890
   448
    /**
jaroslav@1890
   449
     * Attempts to release this lock.
jaroslav@1890
   450
     *
jaroslav@1890
   451
     * <p>If the current thread is the holder of this lock then the hold
jaroslav@1890
   452
     * count is decremented.  If the hold count is now zero then the lock
jaroslav@1890
   453
     * is released.  If the current thread is not the holder of this
jaroslav@1890
   454
     * lock then {@link IllegalMonitorStateException} is thrown.
jaroslav@1890
   455
     *
jaroslav@1890
   456
     * @throws IllegalMonitorStateException if the current thread does not
jaroslav@1890
   457
     *         hold this lock
jaroslav@1890
   458
     */
jaroslav@1890
   459
    public void unlock() {
jaroslav@1890
   460
        sync.release(1);
jaroslav@1890
   461
    }
jaroslav@1890
   462
jaroslav@1890
   463
    /**
jaroslav@1890
   464
     * Returns a {@link Condition} instance for use with this
jaroslav@1890
   465
     * {@link Lock} instance.
jaroslav@1890
   466
     *
jaroslav@1890
   467
     * <p>The returned {@link Condition} instance supports the same
jaroslav@1890
   468
     * usages as do the {@link Object} monitor methods ({@link
jaroslav@1890
   469
     * Object#wait() wait}, {@link Object#notify notify}, and {@link
jaroslav@1890
   470
     * Object#notifyAll notifyAll}) when used with the built-in
jaroslav@1890
   471
     * monitor lock.
jaroslav@1890
   472
     *
jaroslav@1890
   473
     * <ul>
jaroslav@1890
   474
     *
jaroslav@1890
   475
     * <li>If this lock is not held when any of the {@link Condition}
jaroslav@1890
   476
     * {@linkplain Condition#await() waiting} or {@linkplain
jaroslav@1890
   477
     * Condition#signal signalling} methods are called, then an {@link
jaroslav@1890
   478
     * IllegalMonitorStateException} is thrown.
jaroslav@1890
   479
     *
jaroslav@1890
   480
     * <li>When the condition {@linkplain Condition#await() waiting}
jaroslav@1890
   481
     * methods are called the lock is released and, before they
jaroslav@1890
   482
     * return, the lock is reacquired and the lock hold count restored
jaroslav@1890
   483
     * to what it was when the method was called.
jaroslav@1890
   484
     *
jaroslav@1890
   485
     * <li>If a thread is {@linkplain Thread#interrupt interrupted}
jaroslav@1890
   486
     * while waiting then the wait will terminate, an {@link
jaroslav@1890
   487
     * InterruptedException} will be thrown, and the thread's
jaroslav@1890
   488
     * interrupted status will be cleared.
jaroslav@1890
   489
     *
jaroslav@1890
   490
     * <li> Waiting threads are signalled in FIFO order.
jaroslav@1890
   491
     *
jaroslav@1890
   492
     * <li>The ordering of lock reacquisition for threads returning
jaroslav@1890
   493
     * from waiting methods is the same as for threads initially
jaroslav@1890
   494
     * acquiring the lock, which is in the default case not specified,
jaroslav@1890
   495
     * but for <em>fair</em> locks favors those threads that have been
jaroslav@1890
   496
     * waiting the longest.
jaroslav@1890
   497
     *
jaroslav@1890
   498
     * </ul>
jaroslav@1890
   499
     *
jaroslav@1890
   500
     * @return the Condition object
jaroslav@1890
   501
     */
jaroslav@1890
   502
    public Condition newCondition() {
jaroslav@1890
   503
        return sync.newCondition();
jaroslav@1890
   504
    }
jaroslav@1890
   505
jaroslav@1890
   506
    /**
jaroslav@1890
   507
     * Queries the number of holds on this lock by the current thread.
jaroslav@1890
   508
     *
jaroslav@1890
   509
     * <p>A thread has a hold on a lock for each lock action that is not
jaroslav@1890
   510
     * matched by an unlock action.
jaroslav@1890
   511
     *
jaroslav@1890
   512
     * <p>The hold count information is typically only used for testing and
jaroslav@1890
   513
     * debugging purposes. For example, if a certain section of code should
jaroslav@1890
   514
     * not be entered with the lock already held then we can assert that
jaroslav@1890
   515
     * fact:
jaroslav@1890
   516
     *
jaroslav@1890
   517
     * <pre>
jaroslav@1890
   518
     * class X {
jaroslav@1890
   519
     *   ReentrantLock lock = new ReentrantLock();
jaroslav@1890
   520
     *   // ...
jaroslav@1890
   521
     *   public void m() {
jaroslav@1890
   522
     *     assert lock.getHoldCount() == 0;
jaroslav@1890
   523
     *     lock.lock();
jaroslav@1890
   524
     *     try {
jaroslav@1890
   525
     *       // ... method body
jaroslav@1890
   526
     *     } finally {
jaroslav@1890
   527
     *       lock.unlock();
jaroslav@1890
   528
     *     }
jaroslav@1890
   529
     *   }
jaroslav@1890
   530
     * }
jaroslav@1890
   531
     * </pre>
jaroslav@1890
   532
     *
jaroslav@1890
   533
     * @return the number of holds on this lock by the current thread,
jaroslav@1890
   534
     *         or zero if this lock is not held by the current thread
jaroslav@1890
   535
     */
jaroslav@1890
   536
    public int getHoldCount() {
jaroslav@1890
   537
        return sync.getHoldCount();
jaroslav@1890
   538
    }
jaroslav@1890
   539
jaroslav@1890
   540
    /**
jaroslav@1890
   541
     * Queries if this lock is held by the current thread.
jaroslav@1890
   542
     *
jaroslav@1890
   543
     * <p>Analogous to the {@link Thread#holdsLock} method for built-in
jaroslav@1890
   544
     * monitor locks, this method is typically used for debugging and
jaroslav@1890
   545
     * testing. For example, a method that should only be called while
jaroslav@1890
   546
     * a lock is held can assert that this is the case:
jaroslav@1890
   547
     *
jaroslav@1890
   548
     * <pre>
jaroslav@1890
   549
     * class X {
jaroslav@1890
   550
     *   ReentrantLock lock = new ReentrantLock();
jaroslav@1890
   551
     *   // ...
jaroslav@1890
   552
     *
jaroslav@1890
   553
     *   public void m() {
jaroslav@1890
   554
     *       assert lock.isHeldByCurrentThread();
jaroslav@1890
   555
     *       // ... method body
jaroslav@1890
   556
     *   }
jaroslav@1890
   557
     * }
jaroslav@1890
   558
     * </pre>
jaroslav@1890
   559
     *
jaroslav@1890
   560
     * <p>It can also be used to ensure that a reentrant lock is used
jaroslav@1890
   561
     * in a non-reentrant manner, for example:
jaroslav@1890
   562
     *
jaroslav@1890
   563
     * <pre>
jaroslav@1890
   564
     * class X {
jaroslav@1890
   565
     *   ReentrantLock lock = new ReentrantLock();
jaroslav@1890
   566
     *   // ...
jaroslav@1890
   567
     *
jaroslav@1890
   568
     *   public void m() {
jaroslav@1890
   569
     *       assert !lock.isHeldByCurrentThread();
jaroslav@1890
   570
     *       lock.lock();
jaroslav@1890
   571
     *       try {
jaroslav@1890
   572
     *           // ... method body
jaroslav@1890
   573
     *       } finally {
jaroslav@1890
   574
     *           lock.unlock();
jaroslav@1890
   575
     *       }
jaroslav@1890
   576
     *   }
jaroslav@1890
   577
     * }
jaroslav@1890
   578
     * </pre>
jaroslav@1890
   579
     *
jaroslav@1890
   580
     * @return {@code true} if current thread holds this lock and
jaroslav@1890
   581
     *         {@code false} otherwise
jaroslav@1890
   582
     */
jaroslav@1890
   583
    public boolean isHeldByCurrentThread() {
jaroslav@1890
   584
        return sync.isHeldExclusively();
jaroslav@1890
   585
    }
jaroslav@1890
   586
jaroslav@1890
   587
    /**
jaroslav@1890
   588
     * Queries if this lock is held by any thread. This method is
jaroslav@1890
   589
     * designed for use in monitoring of the system state,
jaroslav@1890
   590
     * not for synchronization control.
jaroslav@1890
   591
     *
jaroslav@1890
   592
     * @return {@code true} if any thread holds this lock and
jaroslav@1890
   593
     *         {@code false} otherwise
jaroslav@1890
   594
     */
jaroslav@1890
   595
    public boolean isLocked() {
jaroslav@1890
   596
        return sync.isLocked();
jaroslav@1890
   597
    }
jaroslav@1890
   598
jaroslav@1890
   599
    /**
jaroslav@1890
   600
     * Returns {@code true} if this lock has fairness set true.
jaroslav@1890
   601
     *
jaroslav@1890
   602
     * @return {@code true} if this lock has fairness set true
jaroslav@1890
   603
     */
jaroslav@1890
   604
    public final boolean isFair() {
jaroslav@1890
   605
        return sync instanceof FairSync;
jaroslav@1890
   606
    }
jaroslav@1890
   607
jaroslav@1890
   608
    /**
jaroslav@1890
   609
     * Returns the thread that currently owns this lock, or
jaroslav@1890
   610
     * {@code null} if not owned. When this method is called by a
jaroslav@1890
   611
     * thread that is not the owner, the return value reflects a
jaroslav@1890
   612
     * best-effort approximation of current lock status. For example,
jaroslav@1890
   613
     * the owner may be momentarily {@code null} even if there are
jaroslav@1890
   614
     * threads trying to acquire the lock but have not yet done so.
jaroslav@1890
   615
     * This method is designed to facilitate construction of
jaroslav@1890
   616
     * subclasses that provide more extensive lock monitoring
jaroslav@1890
   617
     * facilities.
jaroslav@1890
   618
     *
jaroslav@1890
   619
     * @return the owner, or {@code null} if not owned
jaroslav@1890
   620
     */
jaroslav@1890
   621
    protected Thread getOwner() {
jaroslav@1890
   622
        return sync.getOwner();
jaroslav@1890
   623
    }
jaroslav@1890
   624
jaroslav@1890
   625
    /**
jaroslav@1890
   626
     * Queries whether any threads are waiting to acquire this lock. Note that
jaroslav@1890
   627
     * because cancellations may occur at any time, a {@code true}
jaroslav@1890
   628
     * return does not guarantee that any other thread will ever
jaroslav@1890
   629
     * acquire this lock.  This method is designed primarily for use in
jaroslav@1890
   630
     * monitoring of the system state.
jaroslav@1890
   631
     *
jaroslav@1890
   632
     * @return {@code true} if there may be other threads waiting to
jaroslav@1890
   633
     *         acquire the lock
jaroslav@1890
   634
     */
jaroslav@1890
   635
    public final boolean hasQueuedThreads() {
jaroslav@1890
   636
        return sync.hasQueuedThreads();
jaroslav@1890
   637
    }
jaroslav@1890
   638
jaroslav@1890
   639
jaroslav@1890
   640
    /**
jaroslav@1890
   641
     * Queries whether the given thread is waiting to acquire this
jaroslav@1890
   642
     * lock. Note that because cancellations may occur at any time, a
jaroslav@1890
   643
     * {@code true} return does not guarantee that this thread
jaroslav@1890
   644
     * will ever acquire this lock.  This method is designed primarily for use
jaroslav@1890
   645
     * in monitoring of the system state.
jaroslav@1890
   646
     *
jaroslav@1890
   647
     * @param thread the thread
jaroslav@1890
   648
     * @return {@code true} if the given thread is queued waiting for this lock
jaroslav@1890
   649
     * @throws NullPointerException if the thread is null
jaroslav@1890
   650
     */
jaroslav@1890
   651
    public final boolean hasQueuedThread(Thread thread) {
jaroslav@1890
   652
        return sync.isQueued(thread);
jaroslav@1890
   653
    }
jaroslav@1890
   654
jaroslav@1890
   655
jaroslav@1890
   656
    /**
jaroslav@1890
   657
     * Returns an estimate of the number of threads waiting to
jaroslav@1890
   658
     * acquire this lock.  The value is only an estimate because the number of
jaroslav@1890
   659
     * threads may change dynamically while this method traverses
jaroslav@1890
   660
     * internal data structures.  This method is designed for use in
jaroslav@1890
   661
     * monitoring of the system state, not for synchronization
jaroslav@1890
   662
     * control.
jaroslav@1890
   663
     *
jaroslav@1890
   664
     * @return the estimated number of threads waiting for this lock
jaroslav@1890
   665
     */
jaroslav@1890
   666
    public final int getQueueLength() {
jaroslav@1890
   667
        return sync.getQueueLength();
jaroslav@1890
   668
    }
jaroslav@1890
   669
jaroslav@1890
   670
    /**
jaroslav@1890
   671
     * Returns a collection containing threads that may be waiting to
jaroslav@1890
   672
     * acquire this lock.  Because the actual set of threads may change
jaroslav@1890
   673
     * dynamically while constructing this result, the returned
jaroslav@1890
   674
     * collection is only a best-effort estimate.  The elements of the
jaroslav@1890
   675
     * returned collection are in no particular order.  This method is
jaroslav@1890
   676
     * designed to facilitate construction of subclasses that provide
jaroslav@1890
   677
     * more extensive monitoring facilities.
jaroslav@1890
   678
     *
jaroslav@1890
   679
     * @return the collection of threads
jaroslav@1890
   680
     */
jaroslav@1890
   681
    protected Collection<Thread> getQueuedThreads() {
jaroslav@1890
   682
        return sync.getQueuedThreads();
jaroslav@1890
   683
    }
jaroslav@1890
   684
jaroslav@1890
   685
    /**
jaroslav@1890
   686
     * Queries whether any threads are waiting on the given condition
jaroslav@1890
   687
     * associated with this lock. Note that because timeouts and
jaroslav@1890
   688
     * interrupts may occur at any time, a {@code true} return does
jaroslav@1890
   689
     * not guarantee that a future {@code signal} will awaken any
jaroslav@1890
   690
     * threads.  This method is designed primarily for use in
jaroslav@1890
   691
     * monitoring of the system state.
jaroslav@1890
   692
     *
jaroslav@1890
   693
     * @param condition the condition
jaroslav@1890
   694
     * @return {@code true} if there are any waiting threads
jaroslav@1890
   695
     * @throws IllegalMonitorStateException if this lock is not held
jaroslav@1890
   696
     * @throws IllegalArgumentException if the given condition is
jaroslav@1890
   697
     *         not associated with this lock
jaroslav@1890
   698
     * @throws NullPointerException if the condition is null
jaroslav@1890
   699
     */
jaroslav@1890
   700
    public boolean hasWaiters(Condition condition) {
jaroslav@1890
   701
        if (condition == null)
jaroslav@1890
   702
            throw new NullPointerException();
jaroslav@1890
   703
        if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject))
jaroslav@1890
   704
            throw new IllegalArgumentException("not owner");
jaroslav@1890
   705
        return sync.hasWaiters((AbstractQueuedSynchronizer.ConditionObject)condition);
jaroslav@1890
   706
    }
jaroslav@1890
   707
jaroslav@1890
   708
    /**
jaroslav@1890
   709
     * Returns an estimate of the number of threads waiting on the
jaroslav@1890
   710
     * given condition associated with this lock. Note that because
jaroslav@1890
   711
     * timeouts and interrupts may occur at any time, the estimate
jaroslav@1890
   712
     * serves only as an upper bound on the actual number of waiters.
jaroslav@1890
   713
     * This method is designed for use in monitoring of the system
jaroslav@1890
   714
     * state, not for synchronization control.
jaroslav@1890
   715
     *
jaroslav@1890
   716
     * @param condition the condition
jaroslav@1890
   717
     * @return the estimated number of waiting threads
jaroslav@1890
   718
     * @throws IllegalMonitorStateException if this lock is not held
jaroslav@1890
   719
     * @throws IllegalArgumentException if the given condition is
jaroslav@1890
   720
     *         not associated with this lock
jaroslav@1890
   721
     * @throws NullPointerException if the condition is null
jaroslav@1890
   722
     */
jaroslav@1890
   723
    public int getWaitQueueLength(Condition condition) {
jaroslav@1890
   724
        if (condition == null)
jaroslav@1890
   725
            throw new NullPointerException();
jaroslav@1890
   726
        if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject))
jaroslav@1890
   727
            throw new IllegalArgumentException("not owner");
jaroslav@1890
   728
        return sync.getWaitQueueLength((AbstractQueuedSynchronizer.ConditionObject)condition);
jaroslav@1890
   729
    }
jaroslav@1890
   730
jaroslav@1890
   731
    /**
jaroslav@1890
   732
     * Returns a collection containing those threads that may be
jaroslav@1890
   733
     * waiting on the given condition associated with this lock.
jaroslav@1890
   734
     * Because the actual set of threads may change dynamically while
jaroslav@1890
   735
     * constructing this result, the returned collection is only a
jaroslav@1890
   736
     * best-effort estimate. The elements of the returned collection
jaroslav@1890
   737
     * are in no particular order.  This method is designed to
jaroslav@1890
   738
     * facilitate construction of subclasses that provide more
jaroslav@1890
   739
     * extensive condition monitoring facilities.
jaroslav@1890
   740
     *
jaroslav@1890
   741
     * @param condition the condition
jaroslav@1890
   742
     * @return the collection of threads
jaroslav@1890
   743
     * @throws IllegalMonitorStateException if this lock is not held
jaroslav@1890
   744
     * @throws IllegalArgumentException if the given condition is
jaroslav@1890
   745
     *         not associated with this lock
jaroslav@1890
   746
     * @throws NullPointerException if the condition is null
jaroslav@1890
   747
     */
jaroslav@1890
   748
    protected Collection<Thread> getWaitingThreads(Condition condition) {
jaroslav@1890
   749
        if (condition == null)
jaroslav@1890
   750
            throw new NullPointerException();
jaroslav@1890
   751
        if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject))
jaroslav@1890
   752
            throw new IllegalArgumentException("not owner");
jaroslav@1890
   753
        return sync.getWaitingThreads((AbstractQueuedSynchronizer.ConditionObject)condition);
jaroslav@1890
   754
    }
jaroslav@1890
   755
jaroslav@1890
   756
    /**
jaroslav@1890
   757
     * Returns a string identifying this lock, as well as its lock state.
jaroslav@1890
   758
     * The state, in brackets, includes either the String {@code "Unlocked"}
jaroslav@1890
   759
     * or the String {@code "Locked by"} followed by the
jaroslav@1890
   760
     * {@linkplain Thread#getName name} of the owning thread.
jaroslav@1890
   761
     *
jaroslav@1890
   762
     * @return a string identifying this lock, as well as its lock state
jaroslav@1890
   763
     */
jaroslav@1890
   764
    public String toString() {
jaroslav@1890
   765
        Thread o = sync.getOwner();
jaroslav@1890
   766
        return super.toString() + ((o == null) ?
jaroslav@1890
   767
                                   "[Unlocked]" :
jaroslav@1890
   768
                                   "[Locked by thread " + o.getName() + "]");
jaroslav@1890
   769
    }
jaroslav@1890
   770
}