Java多线程系列--“JUC锁”05之 非公平锁(二)
n to implementing the {@link Lock} interface, this
93 * class defines methods {@code isLocked} and
94 * {@code getLockQueueLength}, as well as some associated
95 * {@code protected} access methods that may be useful for
96 * instrumentation and monitoring.
97 *
98 *
Serialization of this class behaves in the same way as built-in
99 * locks: a deserialized lock is in the unlocked state, regardless of
100 * its state when serialized.
101 *
102 *
This lock supports a maximum of 2147483647 recursive locks by
103 * the same thread. Attempts to exceed this limit result in
104 * {@link Error} throws from locking methods.
105 *
106 * @since 1.5
107 * @author Doug Lea
108 */
109 public class ReentrantLock implements Lock, java.io.Serializable {
110 private static final long serialVersionUID = 7373984872572414699L;
111 /** Synchronizer providing all implementation mechanics */
112 private final Sync sync;
113
114 /**
115 * Base of synchronization control for this lock. Subclassed
116 * into fair and nonfair versions below. Uses AQS state to
117 * represent the number of holds on the lock.
118 */
119 abstract static class Sync extends AbstractQueuedSynchronizer {
120 private static final long serialVersionUID = -5179523762034025860L;
121
122 /**
123 * Performs {@link Lock#lock}. The main reason for subclassing
124 * is to allow fast path for nonfair version.
125 */
126 abstract void lock();
127
128 /**
129 * Performs non-fair tryLock. tryAcquire is
130 * implemented in subclasses, but both need nonfair
131 * try for trylock method.
132 */
133 final boolean nonfairTryAcquire(int acquires) {
134 final Thread current = Thread.currentThread();
135 int c = getState();
136 if (c == 0) {
137 if (compareAndSetState(0, acquires)) {
138 setExclusiveOwnerThread(current);
139 return true;
140 }
141 }
142 else if (current == getExclusiveOwnerThread()) {
143 int nextc = c + acquires;
144 if (nextc < 0) // overflow
145 throw new Error("Maximum lock count exceeded");
146 setState(nextc);
147 return true;
148 }
149 return false;
150 }
151
152 protected final boolean tryRelease(int releases) {
153 int c = getState() - releases;
154 if (Thread.currentThread() != getExclusiveOwnerThread())
155 throw new IllegalMonitorStateException();
156 boolean free = false;
157 if (c == 0) {
158 free = true;
159 setExclusiveOwnerThread(null);
160 }
161 setState(c);
162 return free;
163 }
164
165 protected final boolean isHeldExclusively() {
166 // While we must in general read state before owner,
167 // we don't need to do so to check if current thread is owner
168 return getExclusiveOwnerThread() == Thread.currentThread();
169 }
170
171 final ConditionObject newCondition() {
172 return new ConditionObject();
173 }
174
175 // Methods relayed from outer class
176
177 final Thread getOwner() {
178 return getState() == 0 null : getExclusiveOwnerThrea