-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
GridCacheLockImpl.java
1544 lines (1197 loc) · 50.5 KB
/
GridCacheLockImpl.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.ignite.internal.processors.datastructures;
import java.io.Externalizable;
import java.io.IOException;
import java.io.InvalidObjectException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.io.ObjectStreamException;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentSkipListSet;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import org.apache.ignite.IgniteCheckedException;
import org.apache.ignite.IgniteCondition;
import org.apache.ignite.IgniteException;
import org.apache.ignite.IgniteInterruptedException;
import org.apache.ignite.IgniteLock;
import org.apache.ignite.IgniteLogger;
import org.apache.ignite.internal.GridKernalContext;
import org.apache.ignite.internal.IgnitionEx;
import org.apache.ignite.internal.processors.cache.GridCacheContext;
import org.apache.ignite.internal.processors.cache.IgniteInternalCache;
import org.apache.ignite.internal.processors.cache.distributed.near.GridNearTxLocal;
import org.apache.ignite.internal.util.typedef.X;
import org.apache.ignite.internal.util.typedef.internal.CU;
import org.apache.ignite.internal.util.typedef.internal.S;
import org.apache.ignite.internal.util.typedef.internal.U;
import org.apache.ignite.internal.processors.cluster.IgniteChangeGlobalStateSupport;
import org.apache.ignite.transactions.TransactionRollbackException;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import static org.apache.ignite.internal.processors.cache.GridCacheUtils.retryTopologySafe;
import static org.apache.ignite.transactions.TransactionConcurrency.PESSIMISTIC;
import static org.apache.ignite.transactions.TransactionIsolation.REPEATABLE_READ;
/**
* Cache reentrant lock implementation based on AbstractQueuedSynchronizer.
*/
public final class GridCacheLockImpl implements GridCacheLockEx, IgniteChangeGlobalStateSupport, Externalizable {
/** */
private static final long serialVersionUID = 0L;
/** Deserialization stash. */
private static final ThreadLocal<String> stash = new ThreadLocal<>();
/** Logger. */
private IgniteLogger log;
/** Reentrant lock name. */
private String name;
/** Removed flag. */
private volatile boolean rmvd;
/** Reentrant lock key. */
private GridCacheInternalKey key;
/** Reentrant lock projection. */
private IgniteInternalCache<GridCacheInternalKey, GridCacheLockState> lockView;
/** Cache context. */
private GridCacheContext ctx;
/** Initialization guard. */
private final AtomicBoolean initGuard = new AtomicBoolean();
/** Initialization latch. */
private final CountDownLatch initLatch = new CountDownLatch(1);
/** Lock that provides non-overlapping processing of updates. */
private Lock updateLock = new ReentrantLock();
/** Internal synchronization object. */
private Sync sync;
/** Flag indicating that every operation on this lock should be interrupted. */
private volatile boolean interruptAll;
/**
* Empty constructor required by {@link Externalizable}.
*/
public GridCacheLockImpl() {
// This instance should never be used directly.
ctx = null;
}
/**
* Synchronization implementation for reentrant lock using AbstractQueuedSynchronizer.
*/
@SuppressWarnings({"CallToThreadYield", "CallToSignalInsteadOfSignalAll"})
private class Sync extends AbstractQueuedSynchronizer {
/** */
private static final long serialVersionUID = 1192457210091910933L;
/** */
private static final long LOCK_FREE = 0;
/** Map containing condition objects. */
private Map<String, ConditionObject> conditionMap;
/** List of condition signal calls on this node. */
private Map<String, Integer> outgoingSignals;
/** Last condition waited on. */
@Nullable
private volatile String lastCondition;
/** True if any node owning the lock had failed. */
private volatile boolean isBroken;
/** UUID of the node that currently owns the lock. */
private volatile UUID currentOwnerNode;
/** ID of the thread that currently owns the lock. */
private volatile long currentOwnerThreadId;
/** UUID of this node. */
private final UUID thisNode;
/** FailoverSafe flag. */
private final boolean failoverSafe;
/** Fairness flag. */
private final boolean fair;
/** Threads that are waiting on this lock. */
private Set<Long> waitingThreads;
/**
* @param state State.
*/
protected Sync(GridCacheLockState state) {
setState(state.get());
thisNode = ctx.localNodeId();
currentOwnerNode = state.getId();
currentOwnerThreadId = state.getThreadId();
conditionMap = new HashMap<>();
outgoingSignals = new HashMap<>();
failoverSafe = state.isFailoverSafe();
fair = state.isFair();
waitingThreads = new ConcurrentSkipListSet<>();
}
/**
*
*/
protected void addOutgoingSignal(String condition) {
int cnt = 0;
if (outgoingSignals.containsKey(condition)) {
cnt = outgoingSignals.get(condition);
// SignalAll has already been called.
if (cnt == 0)
return;
}
outgoingSignals.put(condition, cnt + 1);
}
/**
* @param condition Condition.
*/
protected void addOutgoingSignalAll(String condition) {
outgoingSignals.put(condition, 0);
}
/**
* Process any condition await calls on this node.
*/
private String processAwait() {
if (lastCondition == null)
return null;
String ret = lastCondition;
lastCondition = null;
return ret;
}
/** */
private Map<String, Integer> processSignal() {
Map<String,Integer> ret = new HashMap<>(outgoingSignals);
outgoingSignals.clear();
return ret;
}
/** Interrupt every thread on this node waiting on this lock. */
private synchronized void interruptAll() {
// First release all threads waiting on associated condition queues.
if (!conditionMap.isEmpty()) {
// Temporarily obtain ownership of the lock,
// in order to signal all conditions.
UUID tempUUID = getOwnerNode();
long tempThreadID = currentOwnerThreadId;
setCurrentOwnerNode(thisNode);
currentOwnerThreadId = Thread.currentThread().getId();
for (Condition c : conditionMap.values())
c.signalAll();
// Restore owner node and owner thread.
setCurrentOwnerNode(tempUUID);
currentOwnerThreadId = tempThreadID;
}
// Interrupt any future call to acquire/release on this sync object.
interruptAll = true;
// Interrupt any ongoing transactions.
for (Thread t: getQueuedThreads())
t.interrupt();
}
/** Check if lock is in correct state (i.e. not broken in non-failoversafe mode),
* if not throw {@linkplain IgniteInterruptedException} */
private void validate(final boolean throwInterrupt) {
// Interrupted flag shouldn't be always cleared
// (e.g. lock() method doesn't throw exception and doesn't clear interrupted)
// but should be cleared if this method is called after lock breakage or node stop.
// If interruptAll is set, exception is thrown anyway.
boolean interrupted = Thread.currentThread().isInterrupted();
// Clear interrupt flag.
if (throwInterrupt || interruptAll)
Thread.interrupted();
if (interruptAll)
throw new IgniteException("Lock broken (possible reason: node stopped" +
" or node owning lock failed while in non-failoversafe mode).");
// Global queue should be synchronized only if interrupted exception should be thrown.
if (fair && (throwInterrupt && interrupted) && !interruptAll) {
synchronizeQueue(true, Thread.currentThread());
throw new IgniteInterruptedException("Lock is interrupted.");
}
}
/**
* Sets the number of permits currently acquired on this lock. This method should only be used in {@linkplain
* GridCacheLockImpl#onUpdate(GridCacheLockState)}.
*
* @param permits Number of permits acquired at this reentrant lock.
*/
final synchronized void setPermits(int permits) {
setState(permits);
}
/**
* Gets the number of permissions currently acquired at this lock.
*
* @return Number of permits acquired at this reentrant lock.
*/
final int getPermits() {
return getState();
}
/**
* Sets the UUID of the node that currently owns this lock. This method should only be used in {@linkplain
* GridCacheLockImpl#onUpdate(GridCacheLockState)}.
*
* @param ownerNode UUID of the node owning this lock.
*/
final synchronized void setCurrentOwnerNode(UUID ownerNode) {
currentOwnerNode = ownerNode;
}
/**
* Gets the UUID of the node that currently owns the lock.
*
* @return UUID of the node that currently owns the lock.
*/
final UUID getOwnerNode() {
return currentOwnerNode;
}
/**
* Checks if latest call to acquire/release was called on this node.
* Should only be called from update method.
*
* @param newOwnerID ID of the node that is about to acquire this lock (or null).
* @return true if acquire/release that triggered last update came from this node.
*/
protected boolean isLockedLocally(UUID newOwnerID) {
return thisNode.equals(getOwnerNode()) || thisNode.equals(newOwnerID);
}
/**
* @param newOwnerThreadId New owner thread id.
*/
protected void setCurrentOwnerThread(long newOwnerThreadId) {
currentOwnerThreadId = newOwnerThreadId;
}
/**
* Returns true if node that owned the locked failed before call to unlock.
*
* @return true if any node failed while owning the lock.
*/
protected boolean isBroken() {
return isBroken;
}
/** */
protected void setBroken(boolean isBroken) {
this.isBroken = isBroken;
}
/** */
protected synchronized boolean hasPredecessor(LinkedList<UUID> nodes) {
if (!fair)
return false;
for (Iterator<UUID> it = nodes.iterator(); it.hasNext(); ) {
UUID node = it.next();
if (ctx.discovery().node(node) == null) {
it.remove();
continue;
}
return !node.equals(thisNode);
}
return false;
}
/**
* Performs tryLock.
* @param acquires Number of permits to acquire.
* @param fair Fairness parameter.
* @return {@code True} if succeeded, false otherwise.
*/
final boolean tryAcquire(final int acquires, final boolean fair) {
// If broken in non-failoversafe mode, exit immediately.
if (interruptAll)
return true;
final Thread current = Thread.currentThread();
boolean failed = false;
int c = getState();
// Wait for lock to reach stable state.
while (c != 0) {
UUID currentOwner = currentOwnerNode;
if (currentOwner != null) {
failed = ctx.discovery().node(currentOwner) == null;
break;
}
c = getState();
}
// Check if lock is released or current owner failed.
if (c == 0 || failed) {
if (compareAndSetGlobalState(0, acquires, current, fair)) {
// Not used for synchronization (we use ThreadID), but updated anyway.
setExclusiveOwnerThread(current);
while (!isHeldExclusively() && !interruptAll)
Thread.yield();
return true;
}
}
else if (isHeldExclusively()) {
int nextc = c + acquires;
if (nextc < 0) // overflow
throw new Error("Maximum lock count exceeded.");
setState(nextc);
return true;
}
if (fair && !isQueued(current))
synchronizeQueue(false, current);
return false;
}
/**
* Performs lock.
*/
final void lock() {
acquire(1);
}
/** {@inheritDoc} */
@Override protected final boolean tryAcquire(int acquires) {
return tryAcquire(acquires, fair);
}
/** {@inheritDoc} */
@Override protected final boolean tryRelease(int releases) {
// This method is called with release==0 only when trying to wake through update,
// to check if some other node released the lock.
if (releases == 0)
return true;
// If broken in non-failoversafe mode, exit immediately.
if (interruptAll)
return true;
int c = getState() - releases;
if (!isHeldExclusively()) {
log.error("Lock.unlock() is called in illegal state [callerNodeId=" + thisNode + ", ownerNodeId="
+ currentOwnerNode + ", callerThreadId=" + Thread.currentThread().getId() + ", ownerThreadId="
+ currentOwnerThreadId + ", lockState=" + getState() + "]");
throw new IllegalMonitorStateException();
}
boolean free = false;
if (c == 0) {
free = true;
setGlobalState(0, processAwait(), processSignal());
while (isHeldExclusively() && !interruptAll)
Thread.yield();
}
else
setState(c);
return free;
}
/** {@inheritDoc} */
@Override protected final boolean isHeldExclusively() {
// While we must in general read state before owner,
// we don't need to do so to check if current thread is owner
return currentOwnerThreadId == Thread.currentThread().getId() && thisNode.equals(currentOwnerNode);
}
/**
* @param name Condition name.
* @return Condition object.
*/
final synchronized IgniteCondition newCondition(String name) {
if (conditionMap.containsKey(name))
return new IgniteConditionObject(name, conditionMap.get(name));
ConditionObject cond = new ConditionObject();
conditionMap.put(name, cond);
return new IgniteConditionObject(name, cond);
}
// Methods relayed from outer class
final int getHoldCount() {
return isHeldExclusively() ? getState() : 0;
}
final boolean isLocked() throws IgniteCheckedException {
return getState() != 0 || lockView.get(key).get() != 0;
}
/**
* This method is used for synchronizing the reentrant lock state across all nodes.
*/
boolean compareAndSetGlobalState(final int expVal, final int newVal,
final Thread newThread, final boolean bargingProhibited) {
try {
return retryTopologySafe(new Callable<Boolean>() {
@Override public Boolean call() throws Exception {
try (GridNearTxLocal tx = CU.txStartInternal(ctx, lockView, PESSIMISTIC, REPEATABLE_READ)) {
GridCacheLockState val = lockView.get(key);
if (val == null)
throw new IgniteCheckedException("Failed to find reentrant lock with given name: " + name);
final long newThreadID = newThread.getId();
LinkedList<UUID> nodes = val.getNodes();
// Barging is prohibited in fair mode unless tryLock() is called.
if (!(bargingProhibited && hasPredecessor(nodes))) {
if (val.get() == expVal || ctx.discovery().node(val.getId()) == null) {
val.set(newVal);
val.setId(thisNode);
val.setThreadId(newThreadID);
val.setSignals(null);
// This node is already in queue, except in cases where this is the only node
// or this is a call to tryLock(), in which case barging is ok.
// Queue is only updated if this is fair lock.
if (val.isFair() && (nodes.isEmpty() || !bargingProhibited))
nodes.addFirst(thisNode);
val.setNodes(nodes);
val.setChanged(true);
lockView.put(key, val);
tx.commit();
return true;
}
}
return false;
}
catch (Exception e) {
if (interruptAll) {
log.info("Node is stopped (or lock is broken in non-failover safe mode)," +
" aborting transaction.");
// Return immediately, exception will be thrown later.
return true;
}
else {
if (Thread.currentThread().isInterrupted()) {
log.info("Thread is interrupted while attempting to acquire lock.");
// Delegate the decision to throw InterruptedException to the AQS.
sync.release(0);
return false;
}
U.error(log, "Failed to compare and set: " + this, e);
}
throw e;
}
}
});
}
catch (IgniteCheckedException e) {
throw U.convertException(e);
}
}
/**
* This method is used for synchronizing the number of acquire attempts on this lock across all nodes.
*
* @param cancelled true if acquire attempt is cancelled, false if acquire attempt should be registered.
*/
boolean synchronizeQueue(final boolean cancelled, final Thread thread) {
final AtomicBoolean interrupted = new AtomicBoolean(false);
try {
return retryTopologySafe(new Callable<Boolean>() {
@Override public Boolean call() throws Exception {
try (GridNearTxLocal tx = CU.txStartInternal(ctx, lockView, PESSIMISTIC, REPEATABLE_READ)) {
GridCacheLockState val = lockView.get(key);
if (val == null)
throw new IgniteCheckedException("Failed to find reentrant lock with given name: " + name);
LinkedList<UUID> nodes = val.getNodes();
if (!cancelled) {
nodes.add(thisNode);
val.setChanged(false);
lockView.put(key, val);
tx.commit();
// Keep track of all threads that are queued in global queue.
// We deliberately don't use #sync.isQueued(), because AQS
// cancel threads immediately after throwing interrupted exception.
sync.waitingThreads.add(thread.getId());
return true;
}
else {
if (sync.waitingThreads.contains(thread.getId())) {
// Update other nodes if this is the first node in queue.
val.setChanged(nodes.lastIndexOf(thisNode) == 0);
nodes.removeLastOccurrence(thisNode);
lockView.put(key, val);
tx.commit();
sync.waitingThreads.remove(thread.getId());
return true;
}
}
return false;
}
catch (Exception e) {
if (interruptAll) {
log.info("Node is stopped (or lock is broken in non-failover safe mode)," +
" aborting transaction.");
// Abort this attempt to synchronize queue and start another one,
// that will return immediately.
sync.release(0);
return false;
}
else {
// If thread got interrupted, abort this attempt to synchronize queue,
// clear interrupt flag and try again, and let the AQS decide
// whether to throw an exception or ignore it.
if (Thread.interrupted() || X.hasCause(e, InterruptedException.class)) {
interrupted.set(true);
throw new TransactionRollbackException("Thread got interrupted " +
"while synchronizing the global queue, retrying. ");
}
U.error(log, "Failed to synchronize global lock queue: " + this, e);
}
throw e;
}
}
});
}
catch (IgniteCheckedException e) {
throw U.convertException(e);
}
finally {
// Restore interrupt flag and let AQS decide what to do with it.
if (interrupted.get())
Thread.currentThread().interrupt();
}
}
/**
* Sets the global state across all nodes after releasing the reentrant lock.
*
* @param newVal New state.
* @param lastCond Id of the condition await is called.
* @param outgoingSignals Map containing signal calls on this node since the last acquisition of the lock.
*/
protected boolean setGlobalState(final int newVal,
@Nullable final String lastCond,
final Map<String, Integer> outgoingSignals) {
try {
return retryTopologySafe(new Callable<Boolean>() {
@Override public Boolean call() throws Exception {
try (GridNearTxLocal tx = CU.txStartInternal(ctx, lockView, PESSIMISTIC, REPEATABLE_READ)) {
GridCacheLockState val = lockView.get(key);
if (val == null)
throw new IgniteCheckedException("Failed to find reentrant lock with given name: " + name);
val.set(newVal);
if (newVal == 0) {
val.setId(null);
val.setThreadId(LOCK_FREE);
}
val.setChanged(true);
// If this lock is fair, remove this node from queue.
if (val.isFair() && newVal == 0) {
UUID rmvdNode = val.getNodes().removeFirst();
assert(thisNode.equals(rmvdNode));
}
// Get global condition queue.
Map<String, LinkedList<UUID>> condMap = val.getConditionMap();
// Create map containing signals from this node.
Map<UUID, LinkedList<String>> signalMap = new HashMap<>();
// Put any signal calls on this node to global state.
if (!outgoingSignals.isEmpty()) {
for (String condition : outgoingSignals.keySet()) {
int cnt = outgoingSignals.get(condition);
// Get queue for this condition.
List<UUID> list = condMap.get(condition);
if (list != null && !list.isEmpty()) {
// Check if signalAll was called.
if (cnt == 0)
cnt = list.size();
// Remove from global condition queue.
for (int i = 0; i < cnt; i++) {
if (list.isEmpty())
break;
UUID uuid = list.remove(0);
// Skip if node to be released is not alive anymore.
if (ctx.discovery().node(uuid) == null) {
cnt++;
continue;
}
LinkedList<String> queue = signalMap.get(uuid);
if (queue == null) {
queue = new LinkedList<>();
signalMap.put(uuid, queue);
}
queue.add(condition);
}
}
}
}
val.setSignals(signalMap);
// Check if this release is called after condition.await() call;
// If true, add this node to the global waiting queue.
if (lastCond != null) {
LinkedList<UUID> queue;
//noinspection IfMayBeConditional
if (!condMap.containsKey(lastCond))
// New condition object.
queue = new LinkedList<>();
else
// Existing condition object.
queue = condMap.get(lastCond);
queue.add(thisNode);
condMap.put(lastCond, queue);
}
val.setConditionMap(condMap);
lockView.put(key, val);
tx.commit();
return true;
}
catch (Exception e) {
if (interruptAll) {
log.info("Node is stopped (or lock is broken in non-failover safe mode)," +
" aborting transaction.");
return true;
}
else
U.error(log, "Failed to release: " + this, e);
throw e;
}
}
});
}
catch (IgniteCheckedException e) {
throw U.convertException(e);
}
}
synchronized boolean checkIncomingSignals(GridCacheLockState state) {
if (state.getSignals() == null)
return false;
LinkedList<String> signals = state.getSignals().get(thisNode);
if (signals == null || signals.isEmpty())
return false;
UUID tempUUID = getOwnerNode();
Thread tempThread = getExclusiveOwnerThread();
long tempThreadID = currentOwnerThreadId;
// Temporarily allow current thread to signal condition object.
// This is safe to do because:
// 1. if release was called on this node,
// it was called from currently active thread;
// 2. if release came from a thread on any other node,
// all threads on this node are already blocked.
setCurrentOwnerNode(thisNode);
setExclusiveOwnerThread(Thread.currentThread());
currentOwnerThreadId = Thread.currentThread().getId();
for (String signal: signals)
conditionMap.get(signal).signal();
// Restore owner node and owner thread.
setCurrentOwnerNode(tempUUID);
setExclusiveOwnerThread(tempThread);
currentOwnerThreadId = tempThreadID;
return true;
}
/**
* Condition implementation for {@linkplain IgniteLock}.
*
**/
private class IgniteConditionObject implements IgniteCondition {
/** */
private final String name;
/** */
private final AbstractQueuedSynchronizer.ConditionObject obj;
/**
* @param name Condition name.
* @param obj Condition object.
*/
protected IgniteConditionObject(String name, ConditionObject obj) {
this.name = name;
this.obj = obj;
}
/**
* Name of this condition.
*
* @return name Name of this condition object.
*/
@Override public String name() {
return name;
}
/** {@inheritDoc} */
@Override public void await() throws IgniteInterruptedException {
ctx.kernalContext().gateway().readLock();
try {
if (!isHeldExclusively())
throw new IllegalMonitorStateException();
lastCondition = name;
obj.await();
sync.validate(true);
}
catch (InterruptedException e) {
throw new IgniteInterruptedException(e);
}
finally {
ctx.kernalContext().gateway().readUnlock();
}
}
/** {@inheritDoc} */
@Override public void awaitUninterruptibly() {
ctx.kernalContext().gateway().readLock();
try {
if (!isHeldExclusively())
throw new IllegalMonitorStateException();
lastCondition = name;
obj.awaitUninterruptibly();
sync.validate(false);
}
finally {
ctx.kernalContext().gateway().readUnlock();
}
}
/** {@inheritDoc} */
@Override public long awaitNanos(long nanosTimeout) throws IgniteInterruptedException {
ctx.kernalContext().gateway().readLock();
try {
if (!isHeldExclusively())
throw new IllegalMonitorStateException();
lastCondition = name;
long result = obj.awaitNanos(nanosTimeout);
sync.validate(true);
return result;
}
catch (InterruptedException e) {
throw new IgniteInterruptedException(e);
}
finally {
ctx.kernalContext().gateway().readUnlock();
}
}
/** {@inheritDoc} */
@Override public boolean await(long time, TimeUnit unit) throws IgniteInterruptedException {
ctx.kernalContext().gateway().readLock();
try {
if (!isHeldExclusively())
throw new IllegalMonitorStateException();
lastCondition = name;
boolean result = obj.await(time, unit);
sync.validate(true);
return result;
}
catch (InterruptedException e) {
throw new IgniteInterruptedException(e);
}
finally {
ctx.kernalContext().gateway().readUnlock();
}
}
/** {@inheritDoc} */
@Override public boolean awaitUntil(Date deadline) throws IgniteInterruptedException {
ctx.kernalContext().gateway().readLock();
try {
if (!isHeldExclusively())
throw new IllegalMonitorStateException();
lastCondition = name;
boolean result = obj.awaitUntil(deadline);
sync.validate(true);
return result;
}
catch (InterruptedException e) {
throw new IgniteInterruptedException(e);