Java多线程系列--“JUC锁”05之 非公平锁(三)
d();
179 }
180
181 final int getHoldCount() {
182 return isHeldExclusively() getState() : 0;
183 }
184
185 final boolean isLocked() {
186 return getState() != 0;
187 }
188
189 /**
190 * Reconstitutes this lock instance from a stream.
191 * @param s the stream
192 */
193 private void readObject(java.io.ObjectInputStream s)
194 throws java.io.IOException, ClassNotFoundException {
195 s.defaultReadObject();
196 setState(0); // reset to unlocked state
197 }
198 }
199
200 /**
201 * Sync object for non-fair locks
202 */
203 static final class NonfairSync extends Sync {
204 private static final long serialVersionUID = 7316153563782823691L;
205
206 /**
207 * Performs lock. Try immediate barge, backing up to normal
208 * acquire on failure.
209 */
210 final void lock() {
211 if (compareAndSetState(0, 1))
212 setExclusiveOwnerThread(Thread.currentThread());
213 else
214 acquire(1);
215 }
216
217 protected final boolean tryAcquire(int acquires) {
218 return nonfairTryAcquire(acquires);
219 }
220 }
221
222 /**
223 * Sync object for fair locks
224 */
225 static final class FairSync extends Sync {
226 private static final long serialVersionUID = -3000897897090466540L;
227
228 final void lock() {
229 acquire(1);
230 }
231
232 /**
233 * Fair version of tryAcquire. Don't grant access unless
234 * recursive call or no waiters or is first.
235 */
236 protected final boolean tryAcquire(int acquires) {
237 final Thread current = Thread.currentThread();
238 int c = getState();
239 if (c == 0) {
240 if (!hasQueuedPredecessors() &&
241 compareAndSetState(0, acquires)) {
242 setExclusiveOwnerThread(current);
243 return true;
244 }
245 }
246 else if (current == getExclusiveOwnerThread()) {
247 int nextc = c + acquires;
248 if (nextc < 0)
249 throw new Error("Maximum lock count exceeded");
250 setState(nextc);
251 return true;
252 }
253 return false;
254 }
255 }
256
257 /**
258 * Creates an instance of {@code ReentrantLock}.
259 * This is equivalent to using {@code ReentrantLock(false)}.
260 */
261 public ReentrantLock() {
262 sync = new NonfairSync();
263 }
264
265 /**
266 * Creates an instance of {@code ReentrantLock} with the
267 * given fairness policy.
268 *
269 * @param fair {@code true} if this lock should use a fair ordering policy
270 */
271 public ReentrantLock(boolean fair) {
272 sync = fair new FairSync() : new NonfairSync();
273 }
274
275 /**
276 * Acquires the lock.
277 *
278 *
Acquires the lock if it is not held by another thread and returns
279 * immediately, setting the lock hold count to one.
280 *
281 *
If the current thread already holds the lock then the hold
282 * count is incremented by one and the method returns immediately.
283 *
284 *
If the lock is hel