-
Notifications
You must be signed in to change notification settings - Fork 683
/
DLockService.java
3066 lines (2730 loc) · 110 KB
/
DLockService.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
/*
* Licensed to the Apache Software Foundation (ASF) under one or more contributor license
* agreements. See the NOTICE file distributed with this work for additional information regarding
* copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the License. You may obtain a
* copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.apache.geode.distributed.internal.locks;
import java.io.DataInput;
import java.io.DataOutput;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.CancellationException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.logging.log4j.Logger;
import org.apache.geode.CancelCriterion;
import org.apache.geode.CancelException;
import org.apache.geode.InternalGemFireException;
import org.apache.geode.StatisticsFactory;
import org.apache.geode.SystemFailure;
import org.apache.geode.annotations.Immutable;
import org.apache.geode.annotations.internal.MakeNotStatic;
import org.apache.geode.distributed.DistributedLockService;
import org.apache.geode.distributed.DistributedSystem;
import org.apache.geode.distributed.DistributedSystemDisconnectedException;
import org.apache.geode.distributed.LeaseExpiredException;
import org.apache.geode.distributed.LockNotHeldException;
import org.apache.geode.distributed.LockServiceDestroyedException;
import org.apache.geode.distributed.internal.DistributionManager;
import org.apache.geode.distributed.internal.InternalDistributedSystem;
import org.apache.geode.distributed.internal.ResourceEvent;
import org.apache.geode.distributed.internal.deadlock.UnsafeThreadLocal;
import org.apache.geode.distributed.internal.locks.DLockQueryProcessor.DLockQueryReplyMessage;
import org.apache.geode.distributed.internal.membership.InternalDistributedMember;
import org.apache.geode.internal.Assert;
import org.apache.geode.internal.logging.log4j.LogMarker;
import org.apache.geode.internal.serialization.DataSerializableFixedID;
import org.apache.geode.internal.serialization.DeserializationContext;
import org.apache.geode.internal.serialization.SerializationContext;
import org.apache.geode.internal.serialization.Version;
import org.apache.geode.internal.util.StopWatch;
import org.apache.geode.internal.util.concurrent.FutureResult;
import org.apache.geode.logging.internal.OSProcess;
import org.apache.geode.logging.internal.log4j.api.LogService;
import org.apache.geode.util.internal.GeodeGlossary;
/**
* Implements the distributed locking service with distributed lock grantors.
*
*/
public class DLockService extends DistributedLockService {
private static final Logger logger = LogService.getLogger();
private static final long NOT_GRANTOR_SLEEP = Long
.getLong(GeodeGlossary.GEMFIRE_PREFIX + "DLockService.notGrantorSleep", 100).longValue();
private static final boolean DEBUG_NONGRANTOR_DESTROY_LOOP = Boolean
.getBoolean(GeodeGlossary.GEMFIRE_PREFIX + "DLockService.debug.nonGrantorDestroyLoop");
private static final int DEBUG_NONGRANTOR_DESTROY_LOOP_COUNT = Integer
.getInteger(
GeodeGlossary.GEMFIRE_PREFIX + "DLockService.debug.nonGrantorDestroyLoopCount", 20)
.intValue();
private static final boolean AUTOMATE_FREE_RESOURCES =
Boolean.getBoolean(GeodeGlossary.GEMFIRE_PREFIX + "DLockService.automateFreeResources");
static final int INVALID_LEASE_ID = -1;
/** Unique name for this instance of the named locking service */
protected final String serviceName;
/** DistributionManager for this member */
private final DistributionManager dm;
/**
* DistributedSystem connection for this member (used for DisconnectListener, logging, etc)
*/
protected final InternalDistributedSystem ds;
/** Known lock tokens for this service. Key:Object(name), Value:DLockToken */
private final Map<Object, DLockToken> tokens = new HashMap<Object, DLockToken>();
/**
* True if this member has destroyed this named locking service. Field is volatile only because
* it's referenced in {@link #toString()} (never synchronize in <code>toString</code>).
*/
private volatile boolean destroyed = false;
/**
* True if this is a distributed lock service; false if local to this vm only. TX has a "local"
* lock service which sets this to false.
*/
private final boolean isDistributed;
/** Optional handler for departure of lease holders; used by grantor */
private DLockLessorDepartureHandler lessorDepartureHandler;
/**
* Hook for transactions which allows custom behavior in processing DLockRecoverGrantorMessage
*/
private DLockRecoverGrantorProcessor.MessageProcessor recoverGrantorProcessor;
/** Thread-safe reference to DistributedLockStats */
private final DistributedLockStats dlockStats;
/**
* Protects {@link #lockGrantorId}, {@link #grantor} and {@link #lockGrantorFutureResult}. Final
* granting of a lock occurs under this synchronization and only if <code>lockGrantorId</code>
* matches the grantor that granted the lock.
*/
private final Object lockGrantorIdLock = new Object();
/** Identifies the current grantor for this lock service. */
private LockGrantorId lockGrantorId;
/**
* Local instance of the lock grantor if this process is the grantor. This field is volatile for
* one use: 1) {@link #toString()} which should not use synchronization due to potential for wrong
* lock ordering. Can we make this non-volatile??
*/
private volatile DLockGrantor grantor;
/**
* Count of currently active locks and lock requests. Used to determine if destroy must tell the
* grantor to release all held locks.
*/
private int activeLocks = 0;
/** True if this service should be destroyed in system DisconnectListener */
private final boolean destroyOnDisconnect;
/** True if this service should automatically freeResources */
private final boolean automateFreeResources;
/** Identifies the thread that is destroying this lock service. */
private final ThreadLocal<Boolean> destroyingThread = new ThreadLocal<Boolean>();
/// ** Held during destory and creation of this lock service. */
// private final Object serviceLock = new Object();
/** Protects access to {@link #destroyed} and {@link #activeLocks}. */
private final Object destroyLock = new Object();
/**
* Created by the thread communicating directly with the elder. Other threads will wait on this
* and then use the resulting lockGrantorId. This ensures that only one message is sent to the
* elder and that only one thread does so at a time. Protected by {@link #lockGrantorIdLock} and
* holds a reference to a {@link LockGrantorId}.
* <p>
* Only outbound threads and operations should ever wait on this. Do NOT allow inbound threads to
* use the <code>lockGrantorFutureResult</code>.
*/
private FutureResult lockGrantorFutureResult;
private final DLockStopper stopper;
// -------------------------------------------------------------------------
// State and concurrency construct methods
// -------------------------------------------------------------------------
public boolean isDestroyed() {
synchronized (this.destroyLock) {
if (this.destroyed) {
if (!isCurrentThreadDoingDestroy()) {
return true;
}
}
return false;
}
}
public void checkDestroyed() {
if (isDestroyed()) {
throw generateLockServiceDestroyedException(generateLockServiceDestroyedMessage());
}
}
/**
* Create a new LockServiceDestroyedException for this lock service.
*
* @param message the detail message that explains the exception
* @return new LockServiceDestroyedException
*/
protected LockServiceDestroyedException generateLockServiceDestroyedException(String message) {
return new LockServiceDestroyedException(message);
}
/**
* Returns the string message to use in a LockServiceDestroyedException for this lock service.
*
* @return the detail message that explains LockServiceDestroyedException
*/
protected String generateLockServiceDestroyedMessage() {
return String.format("%s has been destroyed", this);
}
/**
* Returns true if {@link #lockGrantorId} is the same as the specified LockGrantorId. Caller must
* synchronize on {@link #lockGrantorIdLock}.
*
* @param someLockGrantorId the LockGrantorId to check
*/
private boolean checkLockGrantorId(LockGrantorId someLockGrantorId) {
Assert.assertHoldsLock(this.lockGrantorIdLock, true);
if (this.lockGrantorId == null) {
return false;
}
return this.lockGrantorId.sameAs(someLockGrantorId);
}
/**
* Returns true if lockGrantorId is the same as the specified LockGrantorId. Caller must
* synchronize on lockGrantorIdLock.
*
* @param someLockGrantorId the LockGrantorId to check
*/
public boolean isLockGrantorId(LockGrantorId someLockGrantorId) {
synchronized (this.lockGrantorIdLock) {
return checkLockGrantorId(someLockGrantorId);
}
}
private boolean isCurrentThreadDoingDestroy() {
return Boolean.TRUE.equals(this.destroyingThread.get());
}
private void setDestroyingThread() {
this.destroyingThread.set(Boolean.TRUE);
}
private void clearDestroyingThread() {
this.destroyingThread.remove();
}
private InternalDistributedMember getElderId() {
InternalDistributedMember elder = this.dm.getElderId();
if (elder == null) {
this.dm.getSystem().getCancelCriterion().checkCancelInProgress(null);
}
Assert.assertTrue(elder != null);
return elder;
}
/**
* Returns id of the current lock grantor for this service. If necessary, a request will be sent
* to the elder to fetch this information.
*/
public LockGrantorId getLockGrantorId() {
final boolean isDebugEnabled_DLS = logger.isTraceEnabled(LogMarker.DLS_VERBOSE);
boolean ownLockGrantorFutureResult = false;
FutureResult lockGrantorFutureResultRef = null;
long statStart = -1;
LockGrantorId theLockGrantorId = null;
while (theLockGrantorId == null) {
ownLockGrantorFutureResult = false;
try {
Assert.assertHoldsLock(this.destroyLock, false);
synchronized (this.lockGrantorIdLock) {
if (this.lockGrantorFutureResult != null) {
lockGrantorFutureResultRef = this.lockGrantorFutureResult;
} else if (this.lockGrantorId != null) {
return this.lockGrantorId;
} else {
ownLockGrantorFutureResult = true;
lockGrantorFutureResultRef = new FutureResult(this.dm.getCancelCriterion());
if (isDebugEnabled_DLS) {
logger.trace(LogMarker.DLS_VERBOSE,
"[getLockGrantorId] creating lockGrantorFutureResult");
}
this.lockGrantorFutureResult = lockGrantorFutureResultRef;
}
}
statStart = getStats().startGrantorWait();
if (!ownLockGrantorFutureResult) {
LockGrantorId lockGrantorIdRef =
waitForLockGrantorFutureResult(lockGrantorFutureResultRef, 0, TimeUnit.MILLISECONDS);
if (lockGrantorIdRef != null) {
return lockGrantorIdRef;
} else {
continue;
}
}
InternalDistributedMember elder = getElderId();
Assert.assertTrue(elder != null);
GrantorInfo gi = getGrantorRequest();
theLockGrantorId =
new LockGrantorId(this.dm, gi.getId(), gi.getVersionId(), gi.getSerialNumber());
if (isDebugEnabled_DLS) {
logger.trace(LogMarker.DLS_VERBOSE, "[getLockGrantorId] elder says grantor is {}",
theLockGrantorId);
}
// elder tells us to be the grantor...
if (theLockGrantorId.isLocal(getSerialNumber())) {
boolean needsRecovery = gi.needsRecovery();
if (!needsRecovery) {
if (isDebugEnabled_DLS) {
logger.trace(LogMarker.DLS_VERBOSE, "[getLockGrantorId] needsRecovery is false");
}
synchronized (this.lockGrantorIdLock) {
// either no previous grantor or grantor is newer
Assert.assertTrue(
this.lockGrantorId == null || this.lockGrantorId.isNewerThan(theLockGrantorId)
|| this.lockGrantorId.sameAs(theLockGrantorId),
this.lockGrantorId + " should be null or newer than or same as "
+ theLockGrantorId);
}
}
if (!createLocalGrantor(elder, needsRecovery, theLockGrantorId)) {
theLockGrantorId = this.lockGrantorId;
}
}
// elder says another member is the grantor
else {
synchronized (this.lockGrantorIdLock) {
if (!setLockGrantorId(theLockGrantorId)) {
theLockGrantorId = this.lockGrantorId;
}
}
}
} finally {
synchronized (this.lockGrantorIdLock) {
boolean getLockGrantorIdFailed = theLockGrantorId == null;
if (statStart > -1) {
getStats().endGrantorWait(statStart, getLockGrantorIdFailed);
}
if (ownLockGrantorFutureResult) {
// this thread is doing the real work and must finish the future
Assert.assertTrue(this.lockGrantorFutureResult == lockGrantorFutureResultRef);
if (getLockGrantorIdFailed) {
// failed so cancel lockGrantorFutureResult
lockGrantorFutureResultRef.cancel(false);
} else {
// succeeded so set lockGrantorFutureResult
lockGrantorFutureResultRef.set(theLockGrantorId);
}
// null out the reference so it is free for next usage
this.lockGrantorFutureResult = null;
}
}
} // finally block for lockGrantorFutureResult
} // while theLockGrantorId == null
return theLockGrantorId;
}
/**
* Creates a local {@link DLockGrantor}.
*
* if (!createLocalGrantor(xxx)) { theLockGrantorId = this.lockGrantorId; }
*
* @param elder the elder that told us to be the grantor
* @param needsRecovery true if recovery is required
* @param myLockGrantorId lockGrantorId to use
* @return true if successfully created local grantor; false if aborted
*/
private boolean createLocalGrantor(InternalDistributedMember elder, boolean needsRecovery,
LockGrantorId myLockGrantorId) {
DLockGrantor myGrantor =
DLockGrantor.createGrantor(this, myLockGrantorId.getLockGrantorVersion());
if (logger.isTraceEnabled(LogMarker.DLS_VERBOSE)) {
logger.trace(LogMarker.DLS_VERBOSE, "[createLocalGrantor] Calling makeLocalGrantor");
}
return makeLocalGrantor(elder, needsRecovery, myLockGrantorId, myGrantor);
}
private boolean makeLocalGrantor(InternalDistributedMember elder, boolean needsRecovery,
LockGrantorId myLockGrantorId, DLockGrantor myGrantor) {
final boolean isDebugEnabled_DLS = logger.isTraceEnabled(LogMarker.DLS_VERBOSE);
boolean success = false;
try {
synchronized (this.lockGrantorIdLock) {
if (isDestroyed()) {
checkDestroyed(); // exit
}
InternalDistributedMember currentElder = getElderId();
if (!currentElder.equals(elder)) {
// abort because elder changed
if (isDebugEnabled_DLS) {
logger.trace(LogMarker.DLS_VERBOSE,
"Failed to create {} because elder changed from {} to {}", myLockGrantorId, elder,
currentElder);
}
return false; // exit
}
if (this.deposingLockGrantorId != null) {
if (this.deposingLockGrantorId.isNewerThan(myLockGrantorId)) {
if (isDebugEnabled_DLS) {
logger.trace(LogMarker.DLS_VERBOSE, "Failed to create {} because I was deposed by {}",
myLockGrantorId, this.deposingLockGrantorId);
}
this.deposingLockGrantorId = null;
return false; // exit
}
if (isDebugEnabled_DLS) {
logger.trace(LogMarker.DLS_VERBOSE, "{} failed to depose {}",
this.deposingLockGrantorId, myLockGrantorId);
}
// older grantor couldn't depose us, so null it out...
this.deposingLockGrantorId = null;
}
if (!setLockGrantorId(myLockGrantorId, myGrantor)) {
if (isDebugEnabled_DLS) {
logger.trace(LogMarker.DLS_VERBOSE,
"[getLockGrantorId] failed to create {} because current grantor is {}",
myLockGrantorId, this.lockGrantorId);
}
return false; // exit
}
} // release sync on this.lockGrantorIdLock
// do NOT sync while doing recovery (because it waits for replies)
if (needsRecovery) {
boolean recovered =
DLockRecoverGrantorProcessor.recoverLockGrantor(this.dm.getDistributionManagerIds(),
this, // this lock service
myGrantor, this.dm, elder); // the elder that told us to be the grantor
if (!recovered) {
checkDestroyed();
return false; // exit
}
}
// after recovery, resynchronize on lockGrantorIdLock again
// check to see if myLockGrantorId has been deposed
synchronized (this.lockGrantorIdLock) {
if (isDestroyed()) {
checkDestroyed(); // exit
}
if (this.deposingLockGrantorId != null) {
if (this.deposingLockGrantorId.isNewerThan(myLockGrantorId)) {
if (isDebugEnabled_DLS) {
logger.trace(LogMarker.DLS_VERBOSE, "Failed to create {} because I was deposed by {}",
myLockGrantorId, this.deposingLockGrantorId);
}
this.deposingLockGrantorId = null;
return false; // exit
}
if (isDebugEnabled_DLS) {
logger.trace(LogMarker.DLS_VERBOSE, "{} failed to depose {}",
this.deposingLockGrantorId, myLockGrantorId);
}
this.deposingLockGrantorId = null;
}
if (checkLockGrantorId(myLockGrantorId)) {
success = myGrantor.makeReady(true); // do not enforce initializing
}
}
return success; // exit
} catch (VirtualMachineError err) {
SystemFailure.initiateFailure(err);
// If this ever returns, rethrow the error. We're poisoned
// now, so don't let this thread continue.
throw err;
} catch (Error e) {
// Whenever you catch Error or Throwable, you must also
// catch VirtualMachineError (see above). However, there is
// _still_ a possibility that you are dealing with a cascading
// error condition, so you also need to check to see if the JVM
// is still usable:
SystemFailure.checkFailure();
if (isDebugEnabled_DLS) {
logger.trace(LogMarker.DLS_VERBOSE, "[makeLocalGrantor] throwing Error", e);
}
throw e;
} catch (RuntimeException e) {
if (isDebugEnabled_DLS) {
logger.trace(LogMarker.DLS_VERBOSE, "[makeLocalGrantor] throwing RuntimeException", e);
}
throw e;
} finally {
try {
// abort if unsuccessful or if lock service was destroyed
if (!success || isDestroyed()) {
if (isDebugEnabled_DLS) {
logger.trace(LogMarker.DLS_VERBOSE, "[makeLocalGrantor] aborting {} and {}",
myLockGrantorId, myGrantor);
}
nullLockGrantorId(myLockGrantorId);
if (!myGrantor.isDestroyed()) {
myGrantor.destroy();
}
}
} finally {
// assertion: grantor should now be either ready or destroyed!
if (myGrantor.isInitializing() && !dm.getCancelCriterion().isCancelInProgress()) {
logger.error(LogMarker.DLS_MARKER,
"Grantor is still initializing");
}
if (!success && !myGrantor.isDestroyed() && !dm.getCancelCriterion().isCancelInProgress()) {
logger.error(LogMarker.DLS_MARKER,
"Grantor creation was aborted but grantor was not destroyed");
}
}
}
}
/**
* Set {@link #lockGrantorId} to the given new value if the current value is null or is an older
* grantor version. Caller must hold {@link #lockGrantorIdLock}.
*
* @param newLockGrantorId the new value for lockGrantorId
*/
private boolean setLockGrantorId(LockGrantorId newLockGrantorId) {
Assert.assertHoldsLock(this.lockGrantorIdLock, true);
if (equalsLockGrantorId(newLockGrantorId)) {
return true;
} else if (!newLockGrantorId.hasLockGrantorVersion()) {
// proceed with temporary placeholder used by become grantor
this.lockGrantorId = newLockGrantorId;
return true;
} else if (newLockGrantorId.isRemote() && this.lockGrantorId != null
&& this.lockGrantorId.hasLockGrantorVersion()) {
if (logger.isTraceEnabled(LogMarker.DLS_VERBOSE)) {
logger.trace(LogMarker.DLS_VERBOSE, "[setLockGrantorId] tried to replace {} with {}",
this.lockGrantorId, newLockGrantorId);
}
return false;
} else if (newLockGrantorId.isNewerThan(this.lockGrantorId)) {
this.lockGrantorId = newLockGrantorId;
return true;
} else {
return false;
}
}
/**
* Set {@link #lockGrantorId} to the <code>localLockGrantorId</code> if current value is null or
* is an older grantor version. This also atomically sets {@link #grantor} to ensure that the two
* fields are kept in sync. Caller must hold {@link #lockGrantorIdLock}.
*
* @param localLockGrantorId the new value for lockGrantorId
* @param localGrantor the new local intance of DLockGrantor
*/
private boolean setLockGrantorId(LockGrantorId localLockGrantorId, DLockGrantor localGrantor) {
Assert.assertHoldsLock(this.lockGrantorIdLock, true);
Assert.assertTrue(localLockGrantorId.isLocal(getSerialNumber()));
if (setLockGrantorId(localLockGrantorId)) {
this.grantor = localGrantor;
return true;
}
return false;
}
private LockGrantorId deposingLockGrantorId;
/**
* Deposes {@link #lockGrantorId} if <code>newLockGrantorId</code> is newer.
*
* @param newLockGrantorId the new lock grantor
*/
void deposeOlderLockGrantorId(LockGrantorId newLockGrantorId) {
LockGrantorId deposedLockGrantorId = null;
final boolean isDebugEnabled_DLS = logger.isTraceEnabled(LogMarker.DLS_VERBOSE);
synchronized (this.lockGrantorIdLock) {
if (isDebugEnabled_DLS) {
logger.trace(LogMarker.DLS_VERBOSE, "[deposeOlderLockGrantorId] pre-deposing {} for new {}",
deposedLockGrantorId, newLockGrantorId);
}
this.deposingLockGrantorId = newLockGrantorId;
deposedLockGrantorId = this.lockGrantorId;
}
if (deposedLockGrantorId != null && deposedLockGrantorId.hasLockGrantorVersion()
&& newLockGrantorId.isNewerThan(deposedLockGrantorId)) {
if (isDebugEnabled_DLS) {
logger.trace(LogMarker.DLS_VERBOSE,
"[deposeOlderLockGrantorId] post-deposing {} for new {}", deposedLockGrantorId,
newLockGrantorId);
}
nullLockGrantorId(deposedLockGrantorId);
}
}
/**
* Sets {@link #lockGrantorId} to null if the current value equals the expected old value. Caller
* must hold {@link #lockGrantorIdLock}.
*
* @param oldLockGrantorId the expected old value
* @return true if lockGrantorId was set to null
*/
private boolean nullLockGrantorId(LockGrantorId oldLockGrantorId) {
Assert.assertHoldsLock(this.destroyLock, false);
Assert.assertHoldsLock(this.lockGrantorIdLock, false);
if (oldLockGrantorId == null) {
return false;
}
DLockGrantor grantorToDestroy = null;
try {
synchronized (this.lockGrantorIdLock) {
if (equalsLockGrantorId(oldLockGrantorId)
|| (oldLockGrantorId.isLocal(getSerialNumber()) && isMakingLockGrantor())) {
// this.lockGrantorId != null && this.lockGrantorId.isLocal())) {
if (oldLockGrantorId.isLocal(getSerialNumber())
&& isLockGrantorVersion(this.grantor, oldLockGrantorId.getLockGrantorVersion())) {
// need to destroy and remove grantor
grantorToDestroy = this.grantor;
this.grantor = null;
}
this.lockGrantorId = null;
return true;
} else {
return false;
}
}
} finally {
if (grantorToDestroy != null) {
if (logger.isTraceEnabled(LogMarker.DLS_VERBOSE)) {
logger.trace(LogMarker.DLS_VERBOSE, "[nullLockGrantorId] destroying {}",
grantorToDestroy);
}
grantorToDestroy.destroy();
}
}
}
/**
* Returns true if the grantor version of <code>dlockGrantor</code> equals the
* <code>grantorVersion</code>.
*
* @param dlockGrantor the grantor instance to compare to grantorVersion
* @param grantorVersion the grantor version number
* @return true if dlockGrantor is the same grantor version
*/
private boolean isLockGrantorVersion(DLockGrantor dlockGrantor, long grantorVersion) {
if (dlockGrantor == null) {
return false;
}
return dlockGrantor.getVersionId() == grantorVersion;
}
/**
* Returns true if <code>someLockGrantor</code> equals the current {@link #lockGrantorId}.
*
* @return true if someLockGrantor equals the current lockGrantorId
*/
private boolean equalsLockGrantorId(LockGrantorId someLockGrantor) {
Assert.assertHoldsLock(this.lockGrantorIdLock, true);
if (someLockGrantor == null) {
return this.lockGrantorId == null;
}
return someLockGrantor.equals(this.lockGrantorId);
}
/**
* Returns id of the current lock grantor for this service. If necessary, a request will be sent
* to the elder to fetch this information. Unlike getLockGrantorId this call will not become the
* lock grantor.
*/
public LockGrantorId peekLockGrantorId() {
Assert.assertHoldsLock(this.destroyLock, false);
synchronized (this.lockGrantorIdLock) {
LockGrantorId currentLockGrantorId = this.lockGrantorId;
if (currentLockGrantorId != null) {
return currentLockGrantorId;
}
}
long statStart = getStats().startGrantorWait();
LockGrantorId theLockGrantorId = null;
try {
// 1st thread wins the right to request grantor info from elder
GrantorInfo gi = peekGrantor();
InternalDistributedMember lockGrantorMember = gi.getId();
if (lockGrantorMember == null) {
return null;
}
theLockGrantorId =
new LockGrantorId(this.dm, lockGrantorMember, gi.getVersionId(), gi.getSerialNumber());
return theLockGrantorId;
} finally {
boolean getLockGrantorIdFailed = theLockGrantorId == null;
getStats().endGrantorWait(statStart, getLockGrantorIdFailed);
}
}
/**
* Increments {@link #activeLocks} while synchronized on {@link #destroyLock} after calling
* {@link #checkDestroyed()}.
*/
private void incActiveLocks() {
synchronized (this.destroyLock) {
checkDestroyed();
this.activeLocks++;
}
}
/**
* Decrements {@link #activeLocks} while synchronized on {@link #destroyLock}.
*/
private void decActiveLocks() {
synchronized (this.destroyLock) {
this.activeLocks--;
}
}
/**
* Returns lockGrantorId when lockGrantorFutureResultRef has been set by another thread.
*
* @param lockGrantorFutureResultRef FutureResult to wait for
* @param timeToWait how many ms to wait, 0 = forever
* @param timeUnit the unit of measure for timeToWait
* @return the LockGrantorId or null if FutureResult was cancelled
*/
private LockGrantorId waitForLockGrantorFutureResult(FutureResult lockGrantorFutureResultRef,
long timeToWait, final TimeUnit timeUnit) {
LockGrantorId lockGrantorIdRef = null;
while (lockGrantorIdRef == null) {
boolean interrupted = Thread.interrupted();
try {
checkDestroyed();
if (timeToWait == 0) {
lockGrantorIdRef = (LockGrantorId) lockGrantorFutureResultRef.get();
} else {
lockGrantorIdRef = (LockGrantorId) lockGrantorFutureResultRef.get(timeToWait, timeUnit);
}
} catch (TimeoutException e) {
break;
} catch (InterruptedException e) {
interrupted = true;
this.dm.getCancelCriterion().checkCancelInProgress(e);
if (lockGrantorFutureResultRef.isCancelled()) {
// cancelled Future might throw InterruptedException...?
checkDestroyed();
break; // return null
}
continue;
} catch (CancellationException e) { // Future was cancelled
checkDestroyed();
break; // return null
} finally {
if (interrupted) {
Thread.currentThread().interrupt();
}
}
}
return lockGrantorIdRef;
}
/**
* nulls out grantor to force call to elder
*
* @param timeToWait how long to wait for a new grantor. -1 don't wait, 0 no time limit
* @param timeUnit the unit of measure of timeToWait
*/
private void notLockGrantorId(LockGrantorId notLockGrantorId, long timeToWait,
final TimeUnit timeUnit) {
if (notLockGrantorId.isLocal(getSerialNumber())) {
if (logger.isTraceEnabled(LogMarker.DLS_VERBOSE)) {
logger.trace(LogMarker.DLS_VERBOSE,
"notLockGrantorId {} returning early because notGrantor {} was equal to the local dm {}",
this.serviceName, notLockGrantorId, this.dm.getId());
}
// Let the local destroy or processing of transfer do the clear
return;
}
boolean ownLockGrantorFutureResult = false;
FutureResult lockGrantorFutureResultRef = null;
long statStart = -1;
LockGrantorId currentLockGrantorId = null;
try {
Assert.assertHoldsLock(this.destroyLock, false);
synchronized (this.lockGrantorIdLock) {
currentLockGrantorId = this.lockGrantorId;
if (this.lockGrantorFutureResult != null) {
// some other thread is talking to elder
lockGrantorFutureResultRef = this.lockGrantorFutureResult;
} else if (!notLockGrantorId.sameAs(currentLockGrantorId)) {
return;
} else {
// this thread needs to talk to elder
ownLockGrantorFutureResult = true;
lockGrantorFutureResultRef = new FutureResult(this.dm.getCancelCriterion());
this.lockGrantorFutureResult = lockGrantorFutureResultRef;
}
}
statStart = getStats().startGrantorWait();
if (!ownLockGrantorFutureResult) {
if (timeToWait >= 0) {
waitForLockGrantorFutureResult(lockGrantorFutureResultRef, timeToWait, timeUnit);
}
return;
}
InternalDistributedMember elder = getElderId();
Assert.assertTrue(elder != null);
LockGrantorId elderLockGrantorId = null;
GrantorInfo gi = peekGrantor();
if (gi.getId() != null) {
elderLockGrantorId =
new LockGrantorId(this.dm, gi.getId(), gi.getVersionId(), gi.getSerialNumber());
}
if (notLockGrantorId.sameAs(elderLockGrantorId)) {
// elder says that notLockGrantorId is still the grantor...
sleep(NOT_GRANTOR_SLEEP);
return;
} else {
// elder says another member is the grantor
nullLockGrantorId(notLockGrantorId);
if (logger.isTraceEnabled(LogMarker.DLS_VERBOSE)) {
logger.trace(LogMarker.DLS_VERBOSE,
"notLockGrantorId cleared lockGrantorId for service {}", this.serviceName);
}
}
} finally {
synchronized (this.lockGrantorIdLock) {
if (statStart > -1) {
getStats().endGrantorWait(statStart, false);
}
if (ownLockGrantorFutureResult) {
// this thread is doing the real work and must finish the future
Assert.assertTrue(this.lockGrantorFutureResult == lockGrantorFutureResultRef);
// cancel lockGrantorFutureResult
lockGrantorFutureResultRef.cancel(false);
// null out the reference so it is free for next usage
this.lockGrantorFutureResult = null;
}
}
} // finally block for lockGrantorFutureResult
}
/**
* All calls to GrantorRequestProcessor.clearGrantor must come through this synchronization point.
* <p>
* This fixes a deadlock between this.becomeGrantorMonitor and DistributionManager.elderLock
* <p>
* All calls to the elder may result in elder recovery which may call back into dlock and acquire
* synchronization on this.becomeGrantorMonitor.
*/
void clearGrantor(long grantorVersion, boolean withLocks) {
GrantorRequestProcessor.clearGrantor(grantorVersion, this, getSerialNumber(), this.ds,
withLocks);
}
/**
* All calls to GrantorRequestProcessor.getGrantor must come through this synchronization point.
* <p>
* This fixes a deadlock between this.becomeGrantorMonitor and DistributionManager.elderLock
* <p>
* All calls to the elder may result in elder recovery which may call back into dlock and acquire
* synchronization on this.becomeGrantorMonitor.
*/
private GrantorInfo getGrantorRequest() {
return GrantorRequestProcessor.getGrantor(this, getSerialNumber(), this.ds);
}
/**
* All calls to GrantorRequestProcessor.peekGrantor must come through this synchronization point.
* <p>
* This fixes a deadlock between this.becomeGrantorMonitor and DistributionManager.elderLock
* <p>
* All calls to the elder may result in elder recovery which may call back into dlock and acquire
* synchronization on this.becomeGrantorMonitor.
*/
private GrantorInfo peekGrantor() {
return GrantorRequestProcessor.peekGrantor(this, this.ds);
}
/**
* All calls to GrantorRequestProcessor.becomeGrantor must come through this synchronization
* point.
* <p>
* This fixes a deadlock between this.becomeGrantorMonitor and DistributionManager.elderLock
* <p>
* All calls to the elder may result in elder recovery which may call back into dlock and acquire
* synchronization on this.becomeGrantorMonitor.
*/
private GrantorInfo becomeGrantor(InternalDistributedMember predecessor) {
return GrantorRequestProcessor.becomeGrantor(this, getSerialNumber(), predecessor, this.ds);
}
// -------------------------------------------------------------------------
// New external API methods
// -------------------------------------------------------------------------
@Override
public void becomeLockGrantor() {
becomeLockGrantor((InternalDistributedMember) null);
}
public DLockGrantor getGrantor() {
Assert.assertHoldsLock(this.destroyLock, false);
synchronized (this.lockGrantorIdLock) {
return this.grantor;
}
}
public DLockGrantor getGrantorWithNoSync() {
return this.grantor;
}
/**
* @param predecessor non-null if a predecessor asked us to take over for it
*/
private void becomeLockGrantor(InternalDistributedMember predecessor) {
Assert.assertTrue(predecessor == null);
boolean ownLockGrantorFutureResult = false;
FutureResult lockGrantorFutureResultRef = null;
final boolean isDebugEnabled_DLS = logger.isTraceEnabled(LogMarker.DLS_VERBOSE);
LockGrantorId myLockGrantorId = null;
try { // finally handles lockGrantorFutureResult
// loop while other threads control the lockGrantorFutureResult
// terminate loop if other thread has already made us lock grantor
// terminate loop if this thread gets control of lockGrantorFutureResult
while (!ownLockGrantorFutureResult) {
Assert.assertHoldsLock(this.destroyLock, false);
synchronized (this.lockGrantorIdLock) {
if (isCurrentlyOrIsMakingLockGrantor()) {
return;
} else if (this.lockGrantorFutureResult != null) {
// need to wait for other thread controlling lockGrantorFutureResult
lockGrantorFutureResultRef = this.lockGrantorFutureResult;
} else {
// this thread is in control and will procede to become grantor
// create new lockGrantorFutureResult for other threads to block on
ownLockGrantorFutureResult = true;
lockGrantorFutureResultRef = new FutureResult(this.dm.getCancelCriterion());
if (isDebugEnabled_DLS) {
logger.trace(LogMarker.DLS_VERBOSE,
"[becomeLockGrantor] creating lockGrantorFutureResult");
}
this.lockGrantorFutureResult = lockGrantorFutureResultRef;
}
}
if (!ownLockGrantorFutureResult) {
waitForLockGrantorFutureResult(lockGrantorFutureResultRef, 0, TimeUnit.MILLISECONDS);
}
}
// this thread is now in charge of the lockGrantorFutureResult future
getStats().incBecomeGrantorRequests();
// create the new grantor instance in non-ready state...
long tempGrantorVersion = -1;
LockGrantorId tempLockGrantorId =
new LockGrantorId(this.dm, this.dm.getId(), tempGrantorVersion, getSerialNumber());
DLockGrantor myGrantor = DLockGrantor.createGrantor(this, tempGrantorVersion);
try { // finally handles myGrantor
synchronized (this.lockGrantorIdLock) {
Assert.assertTrue(setLockGrantorId(tempLockGrantorId, myGrantor));
}
if (isDebugEnabled_DLS) {
logger.trace(LogMarker.DLS_VERBOSE, "become set lockGrantorId to {} for service {}",
this.lockGrantorId, this.serviceName);
}
InternalDistributedMember elder = getElderId();
Assert.assertTrue(elder != null);
// NOTE: elder currently returns GrantorInfo for the previous grantor
// CONSIDER: add elderCommunicatedWith to GrantorInfo