-
Notifications
You must be signed in to change notification settings - Fork 668
/
StampedLock.java
2179 lines (1942 loc) · 86 KB
/
StampedLock.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This file is available under and governed by the GNU General Public
* License version 2 only, as published by the Free Software Foundation.
* However, the following notice accompanied the original version of this
* file:
*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/publicdomain/zero/1.0/
*/
package java.util.concurrent.locks;
import java.io.IOException;
import java.io.Serializable;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.VarHandle;
import java.util.concurrent.TimeUnit;
import jdk.internal.vm.annotation.ReservedStackAccess;
/**
* A capability-based lock with three modes for controlling read/write
* access. The state of a StampedLock consists of a version and mode.
* Lock acquisition methods return a stamp that represents and
* controls access with respect to a lock state; "try" versions of
* these methods may instead return the special value zero to
* represent failure to acquire access. Lock release and conversion
* methods require stamps as arguments, and fail if they do not match
* the state of the lock. The three modes are:
*
* <ul>
*
* <li><b>Writing.</b> Method {@link #writeLock} possibly blocks
* waiting for exclusive access, returning a stamp that can be used
* in method {@link #unlockWrite} to release the lock. Untimed and
* timed versions of {@code tryWriteLock} are also provided. When
* the lock is held in write mode, no read locks may be obtained,
* and all optimistic read validations will fail.
*
* <li><b>Reading.</b> Method {@link #readLock} possibly blocks
* waiting for non-exclusive access, returning a stamp that can be
* used in method {@link #unlockRead} to release the lock. Untimed
* and timed versions of {@code tryReadLock} are also provided.
*
* <li><b>Optimistic Reading.</b> Method {@link #tryOptimisticRead}
* returns a non-zero stamp only if the lock is not currently held
* in write mode. Method {@link #validate} returns true if the lock
* has not been acquired in write mode since obtaining a given
* stamp. This mode can be thought of as an extremely weak version
* of a read-lock, that can be broken by a writer at any time. The
* use of optimistic mode for short read-only code segments often
* reduces contention and improves throughput. However, its use is
* inherently fragile. Optimistic read sections should only read
* fields and hold them in local variables for later use after
* validation. Fields read while in optimistic mode may be wildly
* inconsistent, so usage applies only when you are familiar enough
* with data representations to check consistency and/or repeatedly
* invoke method {@code validate()}. For example, such steps are
* typically required when first reading an object or array
* reference, and then accessing one of its fields, elements or
* methods.
*
* </ul>
*
* <p>This class also supports methods that conditionally provide
* conversions across the three modes. For example, method {@link
* #tryConvertToWriteLock} attempts to "upgrade" a mode, returning
* a valid write stamp if (1) already in writing mode (2) in reading
* mode and there are no other readers or (3) in optimistic mode and
* the lock is available. The forms of these methods are designed to
* help reduce some of the code bloat that otherwise occurs in
* retry-based designs.
*
* <p>StampedLocks are designed for use as internal utilities in the
* development of thread-safe components. Their use relies on
* knowledge of the internal properties of the data, objects, and
* methods they are protecting. They are not reentrant, so locked
* bodies should not call other unknown methods that may try to
* re-acquire locks (although you may pass a stamp to other methods
* that can use or convert it). The use of read lock modes relies on
* the associated code sections being side-effect-free. Unvalidated
* optimistic read sections cannot call methods that are not known to
* tolerate potential inconsistencies. Stamps use finite
* representations, and are not cryptographically secure (i.e., a
* valid stamp may be guessable). Stamp values may recycle after (no
* sooner than) one year of continuous operation. A stamp held without
* use or validation for longer than this period may fail to validate
* correctly. StampedLocks are serializable, but always deserialize
* into initial unlocked state, so they are not useful for remote
* locking.
*
* <p>Like {@link java.util.concurrent.Semaphore Semaphore}, but unlike most
* {@link Lock} implementations, StampedLocks have no notion of ownership.
* Locks acquired in one thread can be released or converted in another.
*
* <p>The scheduling policy of StampedLock does not consistently
* prefer readers over writers or vice versa. All "try" methods are
* best-effort and do not necessarily conform to any scheduling or
* fairness policy. A zero return from any "try" method for acquiring
* or converting locks does not carry any information about the state
* of the lock; a subsequent invocation may succeed.
*
* <p>Because it supports coordinated usage across multiple lock
* modes, this class does not directly implement the {@link Lock} or
* {@link ReadWriteLock} interfaces. However, a StampedLock may be
* viewed {@link #asReadLock()}, {@link #asWriteLock()}, or {@link
* #asReadWriteLock()} in applications requiring only the associated
* set of functionality.
*
* <p><b>Sample Usage.</b> The following illustrates some usage idioms
* in a class that maintains simple two-dimensional points. The sample
* code illustrates some try/catch conventions even though they are
* not strictly needed here because no exceptions can occur in their
* bodies.
*
* <pre> {@code
* class Point {
* private double x, y;
* private final StampedLock sl = new StampedLock();
*
* // an exclusively locked method
* void move(double deltaX, double deltaY) {
* long stamp = sl.writeLock();
* try {
* x += deltaX;
* y += deltaY;
* } finally {
* sl.unlockWrite(stamp);
* }
* }
*
* // a read-only method
* // upgrade from optimistic read to read lock
* double distanceFromOrigin() {
* long stamp = sl.tryOptimisticRead();
* try {
* retryHoldingLock: for (;; stamp = sl.readLock()) {
* if (stamp == 0L)
* continue retryHoldingLock;
* // possibly racy reads
* double currentX = x;
* double currentY = y;
* if (!sl.validate(stamp))
* continue retryHoldingLock;
* return Math.hypot(currentX, currentY);
* }
* } finally {
* if (StampedLock.isReadLockStamp(stamp))
* sl.unlockRead(stamp);
* }
* }
*
* // upgrade from optimistic read to write lock
* void moveIfAtOrigin(double newX, double newY) {
* long stamp = sl.tryOptimisticRead();
* try {
* retryHoldingLock: for (;; stamp = sl.writeLock()) {
* if (stamp == 0L)
* continue retryHoldingLock;
* // possibly racy reads
* double currentX = x;
* double currentY = y;
* if (!sl.validate(stamp))
* continue retryHoldingLock;
* if (currentX != 0.0 || currentY != 0.0)
* break;
* stamp = sl.tryConvertToWriteLock(stamp);
* if (stamp == 0L)
* continue retryHoldingLock;
* // exclusive access
* x = newX;
* y = newY;
* return;
* }
* } finally {
* if (StampedLock.isWriteLockStamp(stamp))
* sl.unlockWrite(stamp);
* }
* }
*
* // Upgrade read lock to write lock
* void moveIfAtOrigin(double newX, double newY) {
* long stamp = sl.readLock();
* try {
* while (x == 0.0 && y == 0.0) {
* long ws = sl.tryConvertToWriteLock(stamp);
* if (ws != 0L) {
* stamp = ws;
* x = newX;
* y = newY;
* break;
* }
* else {
* sl.unlockRead(stamp);
* stamp = sl.writeLock();
* }
* }
* } finally {
* sl.unlock(stamp);
* }
* }
* }}</pre>
*
* @since 1.8
* @author Doug Lea
*/
/*
* 改进的读写锁
*
* 读锁与读锁共存,写锁与写锁互斥,读锁与写锁也互斥
* 性能较ReentrantReadWriteLock有所提升,
* 原理是加大了CAS的力度,避免了不断地切换线程上下文
*/
public class StampedLock implements Serializable {
/*
* Algorithmic notes:
*
* The design employs elements of Sequence locks
* (as used in linux kernels; see Lameter's
* http://www.lameter.com/gelato2005.pdf
* and elsewhere; see
* Boehm's http://www.hpl.hp.com/techreports/2012/HPL-2012-68.html)
* and Ordered RW locks (see Shirako et al
* http://dl.acm.org/citation.cfm?id=2312015)
*
* Conceptually, the primary state of the lock includes a sequence
* number that is odd when write-locked and even otherwise.
* However, this is offset by a reader count that is non-zero when
* read-locked. The read count is ignored when validating
* "optimistic" seqlock-reader-style stamps. Because we must use
* a small finite number of bits (currently 7) for readers, a
* supplementary reader overflow word is used when the number of
* readers exceeds the count field. We do this by treating the max
* reader count value (RBITS) as a spinlock protecting overflow
* updates.
*
* Waiters use a modified form of CLH lock used in
* AbstractQueuedSynchronizer (see its internal documentation for
* a fuller account), where each node is tagged (field mode) as
* either a reader or writer. Sets of waiting readers are grouped
* (linked) under a common node (field cowait) so act as a single
* node with respect to most CLH mechanics. By virtue of the
* queue structure, wait nodes need not actually carry sequence
* numbers; we know each is greater than its predecessor. This
* simplifies the scheduling policy to a mainly-FIFO scheme that
* incorporates elements of Phase-Fair locks (see Brandenburg &
* Anderson, especially http://www.cs.unc.edu/~bbb/diss/). In
* particular, we use the phase-fair anti-barging rule: If an
* incoming reader arrives while read lock is held but there is a
* queued writer, this incoming reader is queued. (This rule is
* responsible for some of the complexity of method acquireRead,
* but without it, the lock becomes highly unfair.) Method release
* does not (and sometimes cannot) itself wake up cowaiters. This
* is done by the primary thread, but helped by any other threads
* with nothing better to do in methods acquireRead and
* acquireWrite.
*
* These rules apply to threads actually queued. All tryLock forms
* opportunistically try to acquire locks regardless of preference
* rules, and so may "barge" their way in. Randomized spinning is
* used in the acquire methods to reduce (increasingly expensive)
* context switching while also avoiding sustained memory
* thrashing among many threads. We limit spins to the head of
* queue. If, upon wakening, a thread fails to obtain lock, and is
* still (or becomes) the first waiting thread (which indicates
* that some other thread barged and obtained lock), it escalates
* spins (up to MAX_HEAD_SPINS) to reduce the likelihood of
* continually losing to barging threads.
*
* Nearly all of these mechanics are carried out in methods
* acquireWrite and acquireRead, that, as typical of such code,
* sprawl out because actions and retries rely on consistent sets
* of locally cached reads.
*
* As noted in Boehm's paper (above), sequence validation (mainly
* method validate()) requires stricter ordering rules than apply
* to normal volatile reads (of "state"). To force orderings of
* reads before a validation and the validation itself in those
* cases where this is not already forced, we use acquireFence.
* Unlike in that paper, we allow writers to use plain writes.
* One would not expect reorderings of such writes with the lock
* acquisition CAS because there is a "control dependency", but it
* is theoretically possible, so we additionally add a
* storeStoreFence after lock acquisition CAS.
*
* ----------------------------------------------------------------
* Here's an informal proof that plain reads by _successful_
* readers see plain writes from preceding but not following
* writers (following Boehm and the C++ standard [atomics.fences]):
*
* Because of the total synchronization order of accesses to
* volatile long state containing the sequence number, writers and
* _successful_ readers can be globally sequenced.
*
* int x, y;
*
* Writer 1:
* inc sequence (odd - "locked")
* storeStoreFence();
* x = 1; y = 2;
* inc sequence (even - "unlocked")
*
* Successful Reader:
* read sequence (even)
* // must see writes from Writer 1 but not Writer 2
* r1 = x; r2 = y;
* acquireFence();
* read sequence (even - validated unchanged)
* // use r1 and r2
*
* Writer 2:
* inc sequence (odd - "locked")
* storeStoreFence();
* x = 3; y = 4;
* inc sequence (even - "unlocked")
*
* Visibility of writer 1's stores is normal - reader's initial
* read of state synchronizes with writer 1's final write to state.
* Lack of visibility of writer 2's plain writes is less obvious.
* If reader's read of x or y saw writer 2's write, then (assuming
* semantics of C++ fences) the storeStoreFence would "synchronize"
* with reader's acquireFence and reader's validation read must see
* writer 2's initial write to state and so validation must fail.
* But making this "proof" formal and rigorous is an open problem!
* ----------------------------------------------------------------
*
* The memory layout keeps lock state and queue pointers together
* (normally on the same cache line). This usually works well for
* read-mostly loads. In most other cases, the natural tendency of
* adaptive-spin CLH locks to reduce memory contention lessens
* motivation to further spread out contended locations, but might
* be subject to future improvements.
*/
private static final long serialVersionUID = -6001602636862214147L;
/** Number of processors, for spin control */
// 虚拟机可用的CPU(核心)个数,现代处理器一般都大于一个核
private static final int NCPU = Runtime.getRuntime().availableProcessors();
/** Maximum number of retries before enqueuing on acquisition; at least 1 */
private static final int SPINS = (NCPU > 1) ? 1 << 6 : 1; // 64
/** Maximum number of tries before blocking at head on acquisition */
private static final int HEAD_SPINS = (NCPU > 1) ? 1 << 10 : 1; // 1024
/** Maximum number of retries before re-blocking */
private static final int MAX_HEAD_SPINS = (NCPU > 1) ? 1 << 16 : 1; // 65536
/** The period for yielding when waiting for overflow spinlock */
private static final int OVERFLOW_YIELD_RATE = 7; // must be power 2 - 1
/** The number of bits to use for reader count before overflowing */
private static final int LG_READERS = 7;
/*
* 3 stamp modes can be distinguished by examining (m = stamp & ABITS):
* write mode: m == WBIT
* optimistic read mode: m == 0L (even when read lock is held)
* read mode: m > 0L && m <= RFULL (the stamp is a copy of state, but the
* read hold count in the stamp is unused other than to determine mode)
*
* This differs slightly from the encoding of state:
* (state & ABITS) == 0L indicates the lock is currently unlocked.
* (state & ABITS) == RBITS is a special transient value
* indicating spin-locked to manipulate reader bits overflow.
*/
/*
* 读锁标记:1 0000 0001 ~ 1 0111 1110
* 写锁标记:1 1000 0000
* 乐观读锁:1 0000 0000
*/
private static final long RUNIT = 1L; // 0 0000 0001 读锁计数
private static final long WBIT = 1L << LG_READERS; // 0 1000 0000 写锁掩码 (m&ABITS == WBIT)
private static final long RBITS = WBIT - 1L; // 0 0111 1111 读锁掩码(读锁溢出)
private static final long RFULL = RBITS - 1L; // 0 0111 1110 读锁掩码 (0 < m&ABITS <= RFULL)
private static final long ABITS = RBITS | WBIT; // 0 1111 1111 读/写锁状态掩码
// note overlap with ABITS
private static final long SBITS = ~RBITS; // 1 1000 0000(高位全为1,屏蔽读锁)
/** Initial value for lock state; avoids failure value zero. */
private static final long ORIGIN = WBIT << 1; // 1 0000 0000 锁状态的初始值(可以认为是乐观锁标记)
// Special value from cancelled acquire methods so caller can throw IE
private static final long INTERRUPTED = 1L;
// Values for node status; order matters
private static final int WAITING = -1; // 标记后继结点需要阻塞
private static final int CANCELLED = 1; // 标记后继结点需要取消
// Modes for nodes (int not boolean to allow arithmetic)
private static final int RMODE = 0; // 标记后继结点中的线程正在申请读锁
private static final int WMODE = 1; // 标记后继结点中的线程正在申请写锁(头结点也为WMODE)
/** Lock sequence/state */
// 锁的状态标记,要么保存多个读锁,要么保存一个写锁,要么保存一个乐观锁
private transient volatile long state;
/** Head/Tail of CLH queue */
// 等待队列的主线中的首尾结点(主线上没有连续的读锁线程)
private transient volatile WNode whead, wtail;
/** extra reader count when state read count saturated */
// 记录读锁溢出的数量
private transient int readerOverflow;
// views
transient ReadLockView readLockView;
transient WriteLockView writeLockView;
transient ReadWriteLockView readWriteLockView;
// VarHandle mechanics
private static final VarHandle STATE;
private static final VarHandle WHEAD;
private static final VarHandle WTAIL;
private static final VarHandle WNEXT;
private static final VarHandle WSTATUS;
private static final VarHandle WCOWAIT;
static {
try {
MethodHandles.Lookup l = MethodHandles.lookup();
STATE = l.findVarHandle(StampedLock.class, "state", long.class);
WHEAD = l.findVarHandle(StampedLock.class, "whead", WNode.class);
WTAIL = l.findVarHandle(StampedLock.class, "wtail", WNode.class);
WNEXT = l.findVarHandle(WNode.class, "next", WNode.class);
WCOWAIT = l.findVarHandle(WNode.class, "cowait", WNode.class);
WSTATUS = l.findVarHandle(WNode.class, "status", int.class);
} catch(ReflectiveOperationException e) {
throw new ExceptionInInitializerError(e);
}
}
/*▼ 构造方法 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Creates a new lock, initially in unlocked state.
*/
public StampedLock() {
// 初始化锁的状态:0001 0000 0000
state = ORIGIN;
}
/*▲ 构造方法 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ 锁视图 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Returns a plain {@link Lock} view of this StampedLock in which
* the {@link Lock#lock} method is mapped to {@link #readLock},
* and similarly for other methods. The returned Lock does not
* support a {@link Condition}; method {@link Lock#newCondition()}
* throws {@code UnsupportedOperationException}.
*
* @return the lock
*/
// 获取读锁实例
public Lock asReadLock() {
ReadLockView v;
if((v = readLockView) != null) {
return v;
}
return readLockView = new ReadLockView();
}
/**
* Returns a plain {@link Lock} view of this StampedLock in which
* the {@link Lock#lock} method is mapped to {@link #writeLock},
* and similarly for other methods. The returned Lock does not
* support a {@link Condition}; method {@link Lock#newCondition()}
* throws {@code UnsupportedOperationException}.
*
* @return the lock
*/
// 获取写锁实例
public Lock asWriteLock() {
WriteLockView v;
if((v = writeLockView) != null) {
return v;
}
return writeLockView = new WriteLockView();
}
/**
* Returns a {@link ReadWriteLock} view of this StampedLock in
* which the {@link ReadWriteLock#readLock()} method is mapped to
* {@link #asReadLock()}, and {@link ReadWriteLock#writeLock()} to
* {@link #asWriteLock()}.
*
* @return the lock
*/
// 获取读/写锁实例,通过它可以进一步获取读锁和写锁的实例
public ReadWriteLock asReadWriteLock() {
ReadWriteLockView v;
if((v = readWriteLockView) != null) {
return v;
}
return readWriteLockView = new ReadWriteLockView();
}
/*▲ 锁视图 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ 申请读锁 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Non-exclusively acquires the lock, blocking if necessary
* until available.
*
* @return a read stamp that can be used to unlock or convert mode
*/
// 申请读锁,失败后去排队
@ReservedStackAccess
public long readLock() {
long s, next;
// 如果没有排队线程
if(whead == wtail){
// 获取当前的锁状态
long m = (s = state) & ABITS;
// 不存在写锁,且读锁未到溢出边界
if(m<RFULL){
// 更新state
if(casState(s, next = s + RUNIT)){
return next;
}
}
}
// 存在排队线程,或者存在写锁,或者读锁处于溢出边界
return acquireRead(false, 0L);
}
/**
* Non-exclusively acquires the lock if it is immediately available.
*
* @return a read stamp that can be used to unlock or convert mode,
* or zero if the lock is not available
*/
// 申请读锁,如果存在写锁则申请失败,失败后不阻塞,也不再尝试
@ReservedStackAccess
public long tryReadLock() {
long s, m, next;
// 如果当前不存在写锁
while((m = (s = state) & ABITS) != WBIT) {
// 如果读锁未溢出
if(m<RFULL) {
if(casState(s, next = s + RUNIT)) {
return next;
}
// 如果读锁处于溢出边界
} else {
// 尝试增加溢出标记readerOverflow
if((next = tryIncReaderOverflow(s)) != 0L) {
return next;
}
}
}
return 0L;
}
/**
* Non-exclusively acquires the lock if it is available within the
* given time and the current thread has not been interrupted.
* Behavior under timeout and interruption matches that specified
* for method {@link Lock#tryLock(long, TimeUnit)}.
*
* @param time the maximum time to wait for the lock
* @param unit the time unit of the {@code time} argument
*
* @return a read stamp that can be used to unlock or convert mode,
* or zero if the lock is not available
*
* @throws InterruptedException if the current thread is interrupted
* before acquiring the lock
*/
// 申请读锁,超时后失败,未超时则排队(不可阻塞带有中断标记的线程)
@ReservedStackAccess
public long tryReadLock(long time, TimeUnit unit) throws InterruptedException {
long s, m, next, deadline;
// 将当前时间单位下的time换算为纳秒
long nanos = unit.toNanos(time);
// 如果当前线程没有中断标记
if(!Thread.interrupted()) {
// 获取当前的锁状态
m = (s = state) & ABITS;
// 如果当前不存在写锁
if(m != WBIT) {
// 如果锁的数量还没到溢出边界
if(m<RFULL) {
// 更新锁状态
if(casState(s, next = s + RUNIT)) {
return next;
}
// 如果当前锁的数量已经在溢出边界了
} else {
// 尝试增加溢出标记readerOverflow
if((next = tryIncReaderOverflow(s)) != 0L) {
return next;
}
}
}
// 如果已经超时,本次申请失败
if(nanos<=0L) {
return 0L;
}
// 计算截止时间
if((deadline = System.nanoTime() + nanos) == 0L) {
deadline = 1L;
}
// 申请读锁,超时后失败,未超时则排队
if((next = acquireRead(true, deadline)) != INTERRUPTED) {
return next;
}
}
throw new InterruptedException();
}
/**
* Non-exclusively acquires the lock, blocking if necessary
* until available or the current thread is interrupted.
* Behavior under interruption matches that specified
* for method {@link Lock#lockInterruptibly()}.
*
* @return a read stamp that can be used to unlock or convert mode
*
* @throws InterruptedException if the current thread is interrupted
* before acquiring the lock
*/
// 申请读锁,失败后去排队(不可阻塞带有中断标记的线程)
@ReservedStackAccess
public long readLockInterruptibly() throws InterruptedException {
long s, next;
if(!Thread.interrupted()
// bypass acquireRead on common uncontended case
&& ((whead == wtail && ((s = state) & ABITS)<RFULL && casState(s, next = s + RUNIT)) || (next = acquireRead(true, 0L)) != INTERRUPTED))
return next;
throw new InterruptedException();
}
/**
* See above for explanation.
*
* @param interruptible true if should check interrupts and if so return INTERRUPTED
* @param deadline if nonzero, the System.nanoTime value to timeout at (and return zero)
*
* @return next state, or INTERRUPTED
*/
// 申请读锁
private long acquireRead(boolean interruptible, long deadline) {
boolean wasInterrupted = false;
WNode node = null, p;
// 死循环(初始化等待队列,并将当前结点分发到主线/支线)
for(int spins = -1; ; ) {
WNode h;
// 每次自旋进来都获取最新的队头和队尾
h = whead;
p = wtail;
// 如果当前主线没有排队的线程
if(h==p) {
// 小自旋
for(long m, s, ns; ; ) {
// 获取锁的状态
m = (s = state) & ABITS;
ns = 0;
boolean boo = false;
// 如果当前不存在写锁,且读锁未溢出
if(m<RFULL){
// 允许申请锁,读锁计数增一
ns = s + RUNIT;
boo = casState(s, ns);
} else {
// 如果当前不存在写锁,但是读锁处于溢出边缘
if(m<WBIT){
// 尝试增加溢出标记readerOverflow
ns = tryIncReaderOverflow(s);
boo = ns!=0L;
}// if(m<WBIT)
} // if(m<RFULL)
// 即使的溢出,这里依然可以申请到锁
if(boo) {
if(wasInterrupted) {
Thread.currentThread().interrupt();
}
return ns;
} else {
// 如果存在写锁,则进入小自旋,以较低的开销等待锁空闲
if(m>= WBIT) {
// 如果设定了自旋次数,则递减自旋计数
if(spins>0) {
--spins;
Thread.onSpinWait();
} else {
// 自旋结束
if(spins == 0) {
// 获取最新的队头和队尾信息
WNode nh = whead, np = wtail;
// 等待队列与自旋之前的状态一样
if(nh == h && np == p) {
// 跳出自旋去排队
break;
}
// 如果队头或队尾发生了变化,更新h和p的指向
h = nh;
p = np;
// 如果队头不等于队尾,说明此时存在其他排队线程,直接跳出自旋准备去排队
if(h != p) {
break;
}
}
// 设置小自旋次数为64
spins = SPINS;
} // if(spins>0)
} // if(m>=WBIT)
} // if(boo)
} // 小自旋
} // if(h==p)
/*
* 至此,第一阶段的抢锁过程失败了,失败原因可能是:
* 1.存在其他排队线程
* 2.没有排队线程,但存在迟迟不被释放的写锁
*/
// 如果当前还没有等待队列
if(p == null) {
// 初始化等待队列队头
WNode hd = new WNode(WMODE, null);
if(WHEAD.weakCompareAndSet(this, null, hd)) {
// 队尾和队头指向同一个结点
wtail = hd;
}
// 如果存在等待队列,但是还没有属于当前线程的排队结点,则新建一个
} else if(node == null) {
node = new WNode(RMODE, p);
// 如果当前主线没有排队的结点,或者队尾是【写锁线程】在排队
} else if(h == p || p.mode != RMODE) {
// 如果队尾发生了变化,则需要更新队尾
if(node.prev != p) {
node.prev = p;
// 原子地更新队尾为node
} else if(WTAIL.weakCompareAndSet(this, p, node)) {
p.next = node;
// 如果当前结点成功地进入等待队列,则跳出小自旋
break;
}
// 如果当前已经存在排队的节点,且队尾是【读锁线程】在排队,此时要初始化支线了(头插法)
} else if(!WCOWAIT.compareAndSet(p, node.cowait = p.cowait, node)) {
node.cowait = null;
} else {
// 上面支线初始化成功后,直接到了这里,进入支线死循环
for(; ; ) {
WNode pp, c;
Thread w;
// 如果头结点上有支线线程,这里帮忙唤醒一下
if((h = whead) != null
&& (c = h.cowait) != null
&& WCOWAIT.compareAndSet(h, c, c.cowait)
&& (w = c.thread) != null) {
LockSupport.unpark(w);
}
if(Thread.interrupted()) {
if(interruptible) {
return cancelWaiter(node, p, true);
}
wasInterrupted = true;
}
// 如果支线上首个读锁线程已经排在主线队首,或者已经在执行
if(h == (pp = p.prev) || h == p || pp == null) {
long m, s, ns;
do {
if((m = (s = state) & ABITS)<RFULL // 恰好当前的锁状态为读锁,则允许申请读锁
? casState(s, ns = s + RUNIT)
: (m<WBIT && (ns = tryIncReaderOverflow(s)) != 0L)) {
if(wasInterrupted) {
Thread.currentThread().interrupt();
}
// 读锁申请成功,不需要去阻塞了
return ns;
}
} while(m<WBIT);
}
if(whead == h && p.prev == pp) {
long time;
// 支线上首个读锁线程正在执行
if(pp == null || h == p || p.status>0) {
node = null; // throw away
break;
}
if(deadline == 0L) {
time = 0L;
} else if((time = deadline - System.nanoTime())<=0L) {
if(wasInterrupted) {
Thread.currentThread().interrupt();
}
return cancelWaiter(node, p, false);
}
node.thread = Thread.currentThread();
// 还没执行到支线上,或者当前运行的是写锁
if((h != pp || (state & ABITS) == WBIT) && whead == h && p.prev == pp) {
if(time == 0L) {
// 陷入阻塞,醒来后在小自旋中继续活动
LockSupport.park(this);
} else {
LockSupport.parkNanos(this, time);
}
}
node.thread = null;
}
} // 支线死循环
}
} // 死循环
// 死循环(处理等待队列的主线)
for(int spins = -1; ; ) {
WNode h, np, pp;
int ps;
// 如果当前主线没有排队的结点
if((h = whead) == p) {
if(spins<0) {
// 预设自旋1024次
spins = HEAD_SPINS;
} else if(spins<MAX_HEAD_SPINS) {
// 前一次大自旋没成功的话,这里自旋次数翻倍
spins <<= 1;
}
// 进入大自旋,大自旋时,k在递减,而spins不变
for(int k = spins; ; ) { // spin at head
long m, s, ns;
if((m = (s = state) & ABITS)<RFULL // 如果当前锁状态变为读锁,则更新读锁计数
? casState(s, ns = s + RUNIT)
: (m<WBIT && (ns = tryIncReaderOverflow(s)) != 0L)) {
WNode c;
Thread w;
// 读锁申请成功,更新头结点(很重要的一步)
whead = node;
node.prev = null;
// 唤醒该结点支线上所有申请读锁的线程
while((c = node.cowait) != null) {
if(WCOWAIT.compareAndSet(node, c, c.cowait) && (w = c.thread) != null) {
LockSupport.unpark(w);
}
}
if(wasInterrupted) {
Thread.currentThread().interrupt();
}
return ns;
} else if(m >= WBIT && --k<=0) {
// 如果当前锁状态依旧是写锁,则继续自旋,直到自旋条件不成立时才退出
break;
} else {
Thread.onSpinWait();
}
}// 大自旋
} else if(h != null) {
WNode c;
Thread w;
while((c = h.cowait) != null) {
if(WCOWAIT.compareAndSet(h, c, c.cowait) && (w = c.thread) != null) {
LockSupport.unpark(w);
}
}
}
// 主线上仍有排队线程,或当前锁状态是写锁
if(whead == h) {
if((np = node.prev) != p) {
if(np != null) {
(p = np).next = node; // stale
}
} else if((ps = p.status) == 0) {
WSTATUS.compareAndSet(p, 0, WAITING);
} else if(ps == CANCELLED) {
if((pp = p.prev) != null) {
node.prev = pp;
pp.next = node;
}
} else {
long time;
if(deadline == 0L) {
time = 0L;
} else if((time = deadline - System.nanoTime())<=0L) {
return cancelWaiter(node, node, false);
}
node.thread = Thread.currentThread();
if(p.status<0 && (p != h || (state & ABITS) == WBIT) && whead == h && node.prev == p) {
if(time == 0L) {
// 陷入阻塞,醒来后在大自旋中继续活动
LockSupport.park(this);
} else {
LockSupport.parkNanos(this, time);
}
}
node.thread = null;
if(Thread.interrupted()) {
if(interruptible) {
return cancelWaiter(node, node, true);
}
wasInterrupted = true;
}
}
} // if(whead == h)
} // 死循环
}
/**
* Tries to increment readerOverflow by first setting state access bits value to RBITS,
* indicating hold of spinlock, then updating, then releasing.
*
* @param s a reader overflow stamp: (s & ABITS) >= RFULL
*
* @return new stamp on success, else zero
*/
// 尝试增加溢出标记readerOverflow
private long tryIncReaderOverflow(long s) {
assert (s & ABITS) >= RFULL;
if((s & ABITS) == RFULL) {
// 将state从0111 1110更新为0111 1111
if(casState(s, s | RBITS)) {
// 记录读锁溢出的数量
++readerOverflow;
// 将state从0111 1111更新回0111 1110
STATE.setVolatile(this, s);
// 返回s
return s;