这个锁叫可重入锁。它其实语义上和synchronized差不多,但是添加了一些拓展的特性。

A reentrant mutual exclusion Lock with the same basic behavior and semantics as the implicit monitor lock accessed using synchronized methods and statements, but with extended capabilities.

我们重点看看它的源代码实现。

在ReentrantLock类中很大一部分的函数是委托给这个类Sync来完成的。

    /** Synchronizer providing all implementation mechanics */
    private final Sync sync;

Sync继承了AbstractQueuedSynchronizer,声明了lock()的抽象函数,还实现了nonfairTryAcquire的抽象函数。可以看到它是non-fair锁的默认实现方式。

 1     /**
 2      * Base of synchronization control for this lock. Subclassed
 3      * into fair and nonfair versions below. Uses AQS state to
 4      * represent the number of holds on the lock.
 5      */
 6     static abstract class Sync extends AbstractQueuedSynchronizer {
 7         private static final long serialVersionUID = -5179523762034025860L;
 8 
 9         /**
10          * Performs {@link Lock#lock}. The main reason for subclassing
11          * is to allow fast path for nonfair version.
12          */
13         abstract void lock();
14 
15         /**
16          * Performs non-fair tryLock.  tryAcquire is
17          * implemented in subclasses, but both need nonfair
18          * try for trylock method.
19          */
20         final boolean nonfairTryAcquire(int acquires) {
21             final Thread current = Thread.currentThread();
22             int c = getState();
23             if (c == 0) {
24                 if (compareAndSetState(0, acquires)) {
25                     setExclusiveOwnerThread(current);
26                     return true;
27                 }
28             }
29             else if (current == getExclusiveOwnerThread()) {
30                 int nextc = c + acquires;
31                 if (nextc < 0) // overflow
32                     throw new Error("Maximum lock count exceeded");
33                 setState(nextc);
34                 return true;
35             }
36             return false;
37         }
38 
39         protected final boolean tryRelease(int releases) {
40             int c = getState() - releases;
41             if (Thread.currentThread() != getExclusiveOwnerThread())
42                 throw new IllegalMonitorStateException();
43             boolean free = false;
44             if (c == 0) {
45                 free = true;
46                 setExclusiveOwnerThread(null);
47             }
48             setState(c);
49             return free;
50         }
51 
52         protected final boolean isHeldExclusively() {
53             // While we must in general read state before owner,
54             // we don't need to do so to check if current thread is owner
55             return getExclusiveOwnerThread() == Thread.currentThread();
56         }
57 
58         final ConditionObject newCondition() {
59             return new ConditionObject();
60         }
61 
62         // Methods relayed from outer class
63 
64         final Thread getOwner() {
65             return getState() == 0 ? null : getExclusiveOwnerThread();
66         }
67 
68         final int getHoldCount() {
69             return isHeldExclusively() ? getState() : 0;
70         }
71 
72         final boolean isLocked() {
73             return getState() != 0;
74         }
75 
76         /**
77          * Reconstitutes this lock instance from a stream.
78          * @param s the stream
79          */
80         private void readObject(java.io.ObjectInputStream s)
81             throws java.io.IOException, ClassNotFoundException {
82             s.defaultReadObject();
83             setState(0); // reset to unlocked state
84         }
85     }
View Code

相关文章: