-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
ForsetiClient.java
1180 lines (1061 loc) · 43.1 KB
/
ForsetiClient.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
/*
* Copyright (c) 2002-2018 "Neo4j,"
* Neo4j Sweden AB [http://neo4j.com]
*
* This file is part of Neo4j Enterprise Edition. The included source
* code can be redistributed and/or modified under the terms of the
* GNU AFFERO GENERAL PUBLIC LICENSE Version 3
* (http://www.fsf.org/licensing/licenses/agpl-3.0.html) with the
* Commons Clause, as found in the associated LICENSE.txt file.
*
* This program 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 Affero General Public License for more details.
*
* Neo4j object code can be licensed independently from the source
* under separate terms from the AGPL. Inquiries can be directed to:
* licensing@neo4j.com
*
* More information is also available at:
* https://neo4j.com/licensing/
*/
package org.neo4j.kernel.impl.enterprise.lock.forseti;
import org.eclipse.collections.api.block.procedure.primitive.LongProcedure;
import org.eclipse.collections.api.iterator.IntIterator;
import org.eclipse.collections.api.map.primitive.LongIntMap;
import org.eclipse.collections.api.map.primitive.MutableLongIntMap;
import org.eclipse.collections.impl.map.mutable.primitive.LongIntHashMap;
import java.time.Clock;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.LockSupport;
import java.util.function.IntFunction;
import java.util.stream.Stream;
import org.neo4j.collection.pool.Pool;
import org.neo4j.graphdb.TransactionFailureException;
import org.neo4j.graphdb.factory.GraphDatabaseSettings;
import org.neo4j.kernel.DeadlockDetectedException;
import org.neo4j.kernel.impl.enterprise.lock.forseti.ForsetiLockManager.DeadlockResolutionStrategy;
import org.neo4j.kernel.impl.locking.ActiveLock;
import org.neo4j.kernel.impl.locking.LockAcquisitionTimeoutException;
import org.neo4j.kernel.impl.locking.LockClientStateHolder;
import org.neo4j.kernel.impl.locking.LockClientStoppedException;
import org.neo4j.kernel.impl.locking.LockTracer;
import org.neo4j.kernel.impl.locking.LockWaitEvent;
import org.neo4j.kernel.impl.locking.Locks;
import org.neo4j.kernel.impl.locking.ResourceTypes;
import org.neo4j.kernel.impl.util.collection.SimpleBitSet;
import org.neo4j.storageengine.api.lock.AcquireLockTimeoutException;
import org.neo4j.storageengine.api.lock.ResourceType;
import org.neo4j.storageengine.api.lock.WaitStrategy;
import org.neo4j.unsafe.impl.internal.dragons.UnsafeUtil;
import static java.lang.String.format;
// Please note. Except separate test cases for particular classes related to community locking
// see also LockingCompatibilityTestSuite test suite
/**
* These clients act as agents against the lock manager. The clients hold and release locks.
* <p/>
* The Forseti client tracks which locks it already holds, and will only communicate with the global lock manager if
* necessary. Grabbing the same lock multiple times will honor reentrancy et cetera, but the client will track in
* local fields how many times the lock has been grabbed, such that it will only grab and release the lock once from
* the
* global lock manager.
*/
public class ForsetiClient implements Locks.Client
{
/** Id for this client */
private final int clientId;
/** resourceType -> lock map. These are the global lock maps, shared across all clients. */
private final ConcurrentMap<Long,ForsetiLockManager.Lock>[] lockMaps;
/** resourceType -> wait strategy */
private final WaitStrategy<AcquireLockTimeoutException>[] waitStrategies;
/** How to resolve deadlocks. */
private final DeadlockResolutionStrategy deadlockResolutionStrategy;
/** Handle to return client to pool when closed. */
private final Pool<ForsetiClient> clientPool;
/** Look up a client by id */
private final IntFunction<ForsetiClient> clientById;
/**
* The client uses this to track which locks it holds. It is solely an optimization to ensure we don't need to
* coordinate if we grab the same lock multiple times.
* <p/>
* The data structure looks like:
* Array[ resourceType -> Map( resourceId -> num locks ) ]
*/
private final MutableLongIntMap[] sharedLockCounts;
/** @see #sharedLockCounts */
private final MutableLongIntMap[] exclusiveLockCounts;
/**
* Time within which any particular lock should be acquired.
*
* @see GraphDatabaseSettings#lock_acquisition_timeout
*/
private final long lockAcquisitionTimeoutMillis;
private final Clock clock;
/** List of other clients this client is waiting for. */
private final SimpleBitSet waitList = new SimpleBitSet( 64 );
private long waitListCheckPoint;
// To be able to close Locks.Client instance properly we should be able to do couple of things:
// - have a possibility to prevent new clients to come
// - wake up all the waiters and let them go
// - have a possibility to see how many clients are still using us and wait for them to finish
// We need to do all of that to prevent a situation when a closing client will get a lock that will never be
// closed and eventually will block other clients.
private final LockClientStateHolder stateHolder = new LockClientStateHolder();
/**
* For exclusive locks, we only need a single re-usable one per client. We simply CAS this lock into whatever slots
* we want to hold in the global lock map.
*/
private final ExclusiveLock myExclusiveLock = new ExclusiveLock( this );
private volatile boolean hasLocks;
private final ReleaseExclusiveLocksAndClearSharedVisitor releaseExclusiveAndClearSharedVisitor =
new ReleaseExclusiveLocksAndClearSharedVisitor();
private final ReleaseSharedDontCheckExclusiveVisitor releaseSharedDontCheckExclusiveVisitor =
new ReleaseSharedDontCheckExclusiveVisitor();
/**
* When we *wait* for a specific lock to be released to us, we assign it to this field. This helps us during the
* secondary deadlock verification process, where we traverse the waiter/lock-owner dependency graph.
*/
private volatile ForsetiLockManager.Lock waitingForLock;
public ForsetiClient( int id, ConcurrentMap<Long,ForsetiLockManager.Lock>[] lockMaps,
WaitStrategy<AcquireLockTimeoutException>[] waitStrategies, Pool<ForsetiClient> clientPool,
DeadlockResolutionStrategy deadlockResolutionStrategy, IntFunction<ForsetiClient> clientById,
long lockAcquisitionTimeoutMillis, Clock clock )
{
this.clientId = id;
this.lockMaps = lockMaps;
this.waitStrategies = waitStrategies;
this.deadlockResolutionStrategy = deadlockResolutionStrategy;
this.clientPool = clientPool;
this.clientById = clientById;
this.sharedLockCounts = new MutableLongIntMap[lockMaps.length];
this.exclusiveLockCounts = new MutableLongIntMap[lockMaps.length];
this.lockAcquisitionTimeoutMillis = lockAcquisitionTimeoutMillis;
this.clock = clock;
for ( int i = 0; i < sharedLockCounts.length; i++ )
{
sharedLockCounts[i] = new CountableLongIntHashMap();
exclusiveLockCounts[i] = new CountableLongIntHashMap();
}
}
/**
* Reset current client state. Make it ready for next bunch of operations.
* Should be used before factory release client to public usage.
*/
public void reset()
{
stateHolder.reset();
}
@Override
public void acquireShared( LockTracer tracer, ResourceType resourceType, long... resourceIds )
throws AcquireLockTimeoutException
{
hasLocks = true;
stateHolder.incrementActiveClients( this );
LockWaitEvent waitEvent = null;
try
{
// Grab the global lock map we will be using
ConcurrentMap<Long,ForsetiLockManager.Lock> lockMap = lockMaps[resourceType.typeId()];
// And grab our local lock maps
MutableLongIntMap heldShareLocks = sharedLockCounts[resourceType.typeId()];
MutableLongIntMap heldExclusiveLocks = exclusiveLockCounts[resourceType.typeId()];
for ( long resourceId : resourceIds )
{
// First, check if we already hold this as a shared lock
int heldCount = heldShareLocks.getIfAbsent( resourceId, -1 );
if ( heldCount != -1 )
{
// We already have a lock on this, just increment our local reference counter.
heldShareLocks.put( resourceId, Math.incrementExact( heldCount ) );
continue;
}
// Second, check if we hold it as an exclusive lock
if ( heldExclusiveLocks.containsKey( resourceId ) )
{
// We already have an exclusive lock, so just leave that in place.
// When the exclusive lock is released, it will be automatically downgraded to a shared lock,
// since we bumped the share lock reference count.
heldShareLocks.put( resourceId, 1 );
continue;
}
// We don't hold the lock, so we need to grab it via the global lock map
int tries = 0;
SharedLock mySharedLock = null;
long waitStartMillis = clock.millis();
// Retry loop
while ( true )
{
assertValid( waitStartMillis, resourceType, resourceId );
// Check if there is a lock for this entity in the map
ForsetiLockManager.Lock existingLock = lockMap.get( resourceId );
// No lock
if ( existingLock == null )
{
// Try to create a new shared lock
if ( mySharedLock == null )
{
mySharedLock = new SharedLock( this );
}
if ( lockMap.putIfAbsent( resourceId, mySharedLock ) == null )
{
// Success, we now hold the shared lock.
break;
}
else
{
continue;
}
}
// Someone holds shared lock on this entity, try and get in on that action
else if ( existingLock instanceof SharedLock )
{
if ( ((SharedLock) existingLock).acquire( this ) )
{
// Success!
break;
}
}
// Someone holds an exclusive lock on this entity
else if ( existingLock instanceof ExclusiveLock )
{
// We need to wait, just let the loop run.
}
else
{
throw new UnsupportedOperationException( "Unknown lock type: " + existingLock );
}
if ( waitEvent == null )
{
waitEvent = tracer.waitForLock( false, resourceType, resourceId );
}
// And take note of who we are waiting for. This is used for deadlock detection.
waitFor( existingLock, resourceType, resourceId, false, tries++ );
}
// Make a local note about the fact that we now hold this lock
heldShareLocks.put( resourceId, 1 );
}
}
finally
{
if ( waitEvent != null )
{
waitEvent.close();
}
clearWaitList();
waitingForLock = null;
stateHolder.decrementActiveClients();
}
}
@Override
public void acquireExclusive( LockTracer tracer, ResourceType resourceType, long... resourceIds )
throws AcquireLockTimeoutException
{
hasLocks = true;
stateHolder.incrementActiveClients( this );
LockWaitEvent waitEvent = null;
try
{
ConcurrentMap<Long,ForsetiLockManager.Lock> lockMap = lockMaps[resourceType.typeId()];
MutableLongIntMap heldLocks = exclusiveLockCounts[resourceType.typeId()];
for ( long resourceId : resourceIds )
{
int heldCount = heldLocks.getIfAbsent( resourceId, -1 );
if ( heldCount != -1 )
{
// We already have a lock on this, just increment our local reference counter.
heldLocks.put( resourceId, Math.incrementExact( heldCount ) );
continue;
}
// Grab the global lock
ForsetiLockManager.Lock existingLock;
int tries = 0;
long waitStartMillis = clock.millis();
while ( (existingLock = lockMap.putIfAbsent( resourceId, myExclusiveLock )) != null )
{
assertValid( waitStartMillis, resourceType, resourceId );
// If this is a shared lock:
// Given a grace period of tries (to try and not starve readers), grab an update lock and wait
// for it to convert to an exclusive lock.
if ( tries > 50 && existingLock instanceof SharedLock )
{
// Then we should upgrade that lock
SharedLock sharedLock = (SharedLock) existingLock;
if ( tryUpgradeSharedToExclusive( tracer, waitEvent, resourceType, lockMap, resourceId,
sharedLock,
waitStartMillis ) )
{
break;
}
}
if ( waitEvent == null )
{
waitEvent = tracer.waitForLock( true, resourceType, resourceId );
}
waitFor( existingLock, resourceType, resourceId, true, tries++ );
}
heldLocks.put( resourceId, 1 );
}
}
finally
{
if ( waitEvent != null )
{
waitEvent.close();
}
clearWaitList();
waitingForLock = null;
stateHolder.decrementActiveClients();
}
}
@Override
public boolean tryExclusiveLock( ResourceType resourceType, long resourceId )
{
hasLocks = true;
stateHolder.incrementActiveClients( this );
try
{
ConcurrentMap<Long,ForsetiLockManager.Lock> lockMap = lockMaps[resourceType.typeId()];
MutableLongIntMap heldLocks = exclusiveLockCounts[resourceType.typeId()];
int heldCount = heldLocks.getIfAbsent( resourceId, -1 );
if ( heldCount != -1 )
{
// We already have a lock on this, just increment our local reference counter.
heldLocks.put( resourceId, Math.incrementExact( heldCount ) );
return true;
}
// Grab the global lock
ForsetiLockManager.Lock lock;
if ( (lock = lockMap.putIfAbsent( resourceId, myExclusiveLock )) != null )
{
if ( lock instanceof SharedLock && sharedLockCounts[resourceType.typeId()].containsKey( resourceId ) )
{
SharedLock sharedLock = (SharedLock) lock;
if ( sharedLock.tryAcquireUpdateLock( this ) )
{
if ( sharedLock.numberOfHolders() == 1 )
{
heldLocks.put( resourceId, 1 );
return true;
}
else
{
sharedLock.releaseUpdateLock();
return false;
}
}
}
return false;
}
heldLocks.put( resourceId, 1 );
return true;
}
finally
{
stateHolder.decrementActiveClients();
}
}
@Override
public boolean trySharedLock( ResourceType resourceType, long resourceId )
{
hasLocks = true;
stateHolder.incrementActiveClients( this );
try
{
ConcurrentMap<Long,ForsetiLockManager.Lock> lockMap = lockMaps[resourceType.typeId()];
MutableLongIntMap heldShareLocks = sharedLockCounts[resourceType.typeId()];
MutableLongIntMap heldExclusiveLocks = exclusiveLockCounts[resourceType.typeId()];
int heldCount = heldShareLocks.getIfAbsent( resourceId, -1 );
if ( heldCount != -1 )
{
// We already have a lock on this, just increment our local reference counter.
heldShareLocks.put( resourceId, Math.incrementExact( heldCount ) );
return true;
}
if ( heldExclusiveLocks.containsKey( resourceId ) )
{
// We already have an exclusive lock, so just leave that in place. When the exclusive lock is released,
// it will be automatically downgraded to a shared lock, since we bumped the share lock reference count.
heldShareLocks.put( resourceId, 1 );
return true;
}
long waitStartMillis = clock.millis();
while ( true )
{
assertValid( waitStartMillis, resourceType, resourceId );
ForsetiLockManager.Lock existingLock = lockMap.get( resourceId );
if ( existingLock == null )
{
// Try to create a new shared lock
if ( lockMap.putIfAbsent( resourceId, new SharedLock( this ) ) == null )
{
// Success!
break;
}
}
else if ( existingLock instanceof SharedLock )
{
// Note that there is a "safe" race here where someone may be releasing the last reference to a lock
// and thus removing that lock instance (making it unacquirable). In this case, we allow retrying,
// even though this is a try-lock call.
if ( ((SharedLock) existingLock).acquire( this ) )
{
// Success!
break;
}
else if ( ((SharedLock) existingLock).isUpdateLock() )
{
return false;
}
}
else if ( existingLock instanceof ExclusiveLock )
{
return false;
}
else
{
throw new UnsupportedOperationException( "Unknown lock type: " + existingLock );
}
}
heldShareLocks.put( resourceId, 1 );
return true;
}
finally
{
stateHolder.decrementActiveClients();
}
}
@Override
public boolean reEnterShared( ResourceType resourceType, long resourceId )
{
stateHolder.incrementActiveClients( this );
try
{
MutableLongIntMap heldShareLocks = sharedLockCounts[resourceType.typeId()];
MutableLongIntMap heldExclusiveLocks = exclusiveLockCounts[resourceType.typeId()];
int heldCount = heldShareLocks.getIfAbsent( resourceId, -1 );
if ( heldCount != -1 )
{
// We already have a lock on this, just increment our local reference counter.
heldShareLocks.put( resourceId, Math.incrementExact( heldCount ) );
return true;
}
if ( heldExclusiveLocks.containsKey( resourceId ) )
{
// We already have an exclusive lock, so just leave that in place. When the exclusive lock is released,
// it will be automatically downgraded to a shared lock, since we bumped the share lock reference count.
heldShareLocks.put( resourceId, 1 );
return true;
}
// We didn't hold a lock already, so we cannot re-enter.
return false;
}
finally
{
stateHolder.decrementActiveClients();
}
}
@Override
public boolean reEnterExclusive( ResourceType resourceType, long resourceId )
{
stateHolder.incrementActiveClients( this );
try
{
MutableLongIntMap heldLocks = exclusiveLockCounts[resourceType.typeId()];
int heldCount = heldLocks.getIfAbsent( resourceId, -1 );
if ( heldCount != -1 )
{
// We already have a lock on this, just increment our local reference counter.
heldLocks.put( resourceId, Math.incrementExact( heldCount ) );
return true;
}
// We didn't hold a lock already, so we cannot re-enter.
return false;
}
finally
{
stateHolder.decrementActiveClients();
}
}
@Override
public void releaseShared( ResourceType resourceType, long... resourceIds )
{
stateHolder.incrementActiveClients( this );
try
{
MutableLongIntMap sharedLocks = sharedLockCounts[resourceType.typeId()];
MutableLongIntMap exclusiveLocks = exclusiveLockCounts[resourceType.typeId()];
ConcurrentMap<Long,ForsetiLockManager.Lock> resourceTypeLocks = lockMaps[resourceType.typeId()];
for ( long resourceId : resourceIds )
{
if ( releaseLocalLock( resourceType, resourceId, sharedLocks ) )
{
continue;
}
// Only release if we were not holding an exclusive lock as well
if ( !exclusiveLocks.containsKey( resourceId ) )
{
releaseGlobalLock( resourceTypeLocks, resourceId );
}
}
}
finally
{
stateHolder.decrementActiveClients();
}
}
@Override
public void releaseExclusive( ResourceType resourceType, long... resourceIds )
{
stateHolder.incrementActiveClients( this );
try
{
ConcurrentMap<Long,ForsetiLockManager.Lock> resourceTypeLocks = lockMaps[resourceType.typeId()];
MutableLongIntMap exclusiveLocks = exclusiveLockCounts[resourceType.typeId()];
MutableLongIntMap sharedLocks = sharedLockCounts[resourceType.typeId()];
for ( long resourceId : resourceIds )
{
if ( releaseLocalLock( resourceType, resourceId, exclusiveLocks ) )
{
continue;
}
if ( sharedLocks.containsKey( resourceId ) )
{
// We are still holding a shared lock, so we will release it to be reused
ForsetiLockManager.Lock lock = resourceTypeLocks.get( resourceId );
if ( lock instanceof SharedLock )
{
SharedLock sharedLock = (SharedLock) lock;
if ( sharedLock.isUpdateLock() )
{
sharedLock.releaseUpdateLock();
}
else
{
throw new IllegalStateException( "Incorrect state of exclusive lock. Lock should be updated " +
"to exclusive before attempt to release it. Lock: " + this );
}
}
else
{
// in case if current lock is exclusive we swap it to new shared lock
SharedLock sharedLock = new SharedLock( this );
resourceTypeLocks.put( resourceId, sharedLock );
}
}
else
{
// we do not hold shared lock so we just releasing it
releaseGlobalLock( resourceTypeLocks, resourceId );
}
}
}
finally
{
stateHolder.decrementActiveClients();
}
}
private void releaseAllClientLocks()
{
// Force the release of all locks held.
for ( int i = 0; i < exclusiveLockCounts.length; i++ )
{
MutableLongIntMap exclusiveLocks = exclusiveLockCounts[i];
MutableLongIntMap sharedLocks = sharedLockCounts[i];
// Begin releasing exclusive locks, as we may hold both exclusive and shared locks on the same resource,
// and so releasing exclusive locks means we can "throw away" our shared lock (which would normally have
// been re-instated after releasing the exclusive lock).
if ( exclusiveLocks != null )
{
int size = exclusiveLocks.size();
exclusiveLocks.forEachKey(
releaseExclusiveAndClearSharedVisitor.initialize( sharedLocks, lockMaps[i] ) );
if ( size <= 32 )
{
// If the map is small, its fast and nice to GC to clear it. However, if its large, it is
// 1) Faster to simply allocate a new one and
// 2) Safer, because we guard against clients getting giant maps over time
if ( size > 0 )
{
exclusiveLocks.clear();
}
}
else
{
exclusiveLockCounts[i] = new LongIntHashMap();
}
}
// Then release all remaining shared locks
if ( sharedLocks != null )
{
int size = sharedLocks.size();
sharedLocks.forEachKey( releaseSharedDontCheckExclusiveVisitor.initialize( lockMaps[i] ) );
if ( size <= 32 )
{
// If the map is small, its fast and nice to GC to clear it. However, if its large, it is
// 1) Faster to simply allocate a new one and
// 2) Safer, because we guard against clients getting giant maps over time
if ( size > 0 )
{
sharedLocks.clear();
}
}
else
{
sharedLockCounts[i] = new LongIntHashMap();
}
}
}
}
@Override
public void prepare()
{
stateHolder.prepare( this );
}
@Override
public void stop()
{
// marking client as closed
if ( stateHolder.stopClient() )
{
// waiting for all operations to be completed
waitForAllClientsToLeave();
releaseAllLocks();
}
}
private void waitForAllClientsToLeave()
{
while ( stateHolder.hasActiveClients() )
{
try
{
Thread.sleep( 10 );
}
catch ( InterruptedException e )
{
Thread.interrupted();
}
}
}
@Override
public void close()
{
stateHolder.closeClient();
waitForAllClientsToLeave();
releaseAllLocks();
clientPool.release( this );
}
private void releaseAllLocks()
{
if ( hasLocks )
{
releaseAllClientLocks();
clearWaitList();
hasLocks = false;
}
}
@Override
public int getLockSessionId()
{
return clientId;
}
@Override
public Stream<ActiveLock> activeLocks()
{
List<ActiveLock> locks = new ArrayList<>();
collectActiveLocks( exclusiveLockCounts, locks, ActiveLock.Factory.EXCLUSIVE_LOCK );
collectActiveLocks( sharedLockCounts, locks, ActiveLock.Factory.SHARED_LOCK );
return locks.stream();
}
@Override
public long activeLockCount()
{
return countLocks( exclusiveLockCounts ) + countLocks( sharedLockCounts );
}
private static void collectActiveLocks(
LongIntMap[] counts,
List<ActiveLock> locks,
ActiveLock.Factory activeLock )
{
for ( int typeId = 0; typeId < counts.length; typeId++ )
{
LongIntMap lockCounts = counts[typeId];
if ( lockCounts != null )
{
ResourceType resourceType = ResourceTypes.fromId( typeId );
lockCounts.forEachKeyValue( ( resourceId, count ) -> locks.add( activeLock.create( resourceType, resourceId ) ) );
}
}
}
private long countLocks( LongIntMap[] lockCounts )
{
long count = 0;
for ( LongIntMap lockCount : lockCounts )
{
if ( lockCount != null )
{
count += lockCount.size();
}
}
return count;
}
int waitListSize()
{
return waitList.size();
}
void copyWaitListTo( SimpleBitSet other )
{
other.put( waitList );
}
boolean isWaitingFor( int clientId )
{
return clientId != this.clientId && waitList.contains( clientId );
}
@Override
public boolean equals( Object o )
{
if ( this == o )
{
return true;
}
if ( o == null || getClass() != o.getClass() )
{
return false;
}
ForsetiClient that = (ForsetiClient) o;
return clientId == that.clientId;
}
@Override
public int hashCode()
{
return clientId;
}
@Override
public String toString()
{
return String.format( "ForsetiClient[%d]", clientId );
}
/** Release a lock from the global pool. */
private void releaseGlobalLock( ConcurrentMap<Long,ForsetiLockManager.Lock> lockMap, long resourceId )
{
ForsetiLockManager.Lock lock = lockMap.get( resourceId );
if ( lock instanceof ExclusiveLock )
{
lockMap.remove( resourceId );
}
else if ( lock instanceof SharedLock && ((SharedLock) lock).release( this ) )
{
// We were the last to hold this lock, it is now dead and we should remove it.
// Also cleaning updater reference that can hold lock in memory
((SharedLock) lock).cleanUpdateHolder();
lockMap.remove( resourceId );
}
}
/** Release a lock locally, and return true if we still hold more references to that lock. */
private boolean releaseLocalLock( ResourceType type, long resourceId, MutableLongIntMap localLocks )
{
int lockCount = localLocks.removeKeyIfAbsent( resourceId, -1 );
if ( lockCount == -1 )
{
throw new IllegalStateException( this + " cannot release lock that it does not hold: " +
type + "[" + resourceId + "]." );
}
if ( lockCount > 1 )
{
localLocks.put( resourceId, lockCount - 1 );
return true;
}
return false;
}
/**
* Attempt to upgrade a share lock to an exclusive lock, grabbing the share lock if we don't hold it.
**/
private boolean tryUpgradeSharedToExclusive(
LockTracer tracer,
LockWaitEvent waitEvent,
ResourceType resourceType,
ConcurrentMap<Long,ForsetiLockManager.Lock> lockMap,
long resourceId,
SharedLock sharedLock,
long waitStartMillis )
throws AcquireLockTimeoutException
{
int tries = 0;
boolean holdsSharedLock = sharedLockCounts[resourceType.typeId()].containsKey( resourceId );
if ( !holdsSharedLock )
{
// We don't hold the shared lock, we need to grab it to upgrade it to an exclusive one
if ( !sharedLock.acquire( this ) )
{
return false;
}
try
{
if ( tryUpgradeToExclusiveWithShareLockHeld( tracer, waitEvent, resourceType, resourceId, sharedLock,
tries, waitStartMillis ) )
{
return true;
}
else
{
releaseGlobalLock( lockMap, resourceId );
return false;
}
}
catch ( Throwable e )
{
releaseGlobalLock( lockMap, resourceId );
throw e;
}
}
else
{
// We do hold the shared lock, so no reason to deal with the complexity in the case above.
return tryUpgradeToExclusiveWithShareLockHeld( tracer, waitEvent, resourceType, resourceId, sharedLock,
tries, waitStartMillis );
}
}
/** Attempt to upgrade a share lock that we hold to an exclusive lock. */
private boolean tryUpgradeToExclusiveWithShareLockHeld(
LockTracer tracer, LockWaitEvent priorEvent, ResourceType resourceType, long resourceId,
SharedLock sharedLock, int tries, long waitStartMillis ) throws AcquireLockTimeoutException
{
if ( sharedLock.tryAcquireUpdateLock( this ) )
{
LockWaitEvent waitEvent = null;
try
{
// Now we just wait for all clients to release the the share lock
while ( sharedLock.numberOfHolders() > 1 )
{
assertValid( waitStartMillis, resourceType, resourceId );
if ( waitEvent == null && priorEvent == null )
{
waitEvent = tracer.waitForLock( true, resourceType, resourceId );
}
waitFor( sharedLock, resourceType, resourceId, true, tries++ );
}
return true;
}
catch ( Throwable e )
{
sharedLock.releaseUpdateLock();
if ( e instanceof DeadlockDetectedException || e instanceof LockClientStoppedException )
{
throw (RuntimeException) e;
}
throw new TransactionFailureException( "Failed to upgrade shared lock to exclusive: " + sharedLock, e );
}
finally
{
if ( waitEvent != null )
{
waitEvent.close();
}
clearWaitList();
waitingForLock = null;
}
}
return false;
}
private void clearWaitList()
{
waitListCheckPoint = waitList.checkPointAndPut( waitListCheckPoint, clientId );
}
private void waitFor( ForsetiLockManager.Lock lock, ResourceType type, long resourceId, boolean exclusive, int tries )
{
waitingForLock = lock;
clearAndCopyWaitList( lock );
waitStrategies[type.typeId()].apply( tries );
int b = lock.detectDeadlock( id() );
if ( b != -1 && deadlockResolutionStrategy.shouldAbort( this, clientById.apply( b ) ) )
{
// Force the operations below to happen after the reads we do for deadlock
// detection in the lines above, as a way to cut down on false-positive deadlocks
UnsafeUtil.loadFence();
// Create message before we clear the wait-list, to lower the chance of the message being insane
String message = this + " can't acquire " + lock + " on " + type + "(" + resourceId +
"), because holders of that lock " +
"are waiting for " + this + ".\n Wait list:" + lock.describeWaitList();
// Minimize the risk of false positives by double-checking that the deadlock remains
// after we've generated a description of it.
if ( lock.detectDeadlock( id() ) != -1 )
{
// If the deadlock is real, then an owner of this lock must be (transitively) waiting on a lock that
// we own. So to verify the deadlock, we traverse the lock owners and their `waitingForLock` fields,
// to find a lock that has us among the owners.
// We only act upon the result of this method if the `tries` count is above some threshold. The reason
// is that the Lock.collectOwners, which is algorithm relies upon, is inherently racy, and so only
// reduces the probably of a false positive, but does not eliminate them.
if ( isDeadlockReal( lock, tries ) )
{
// After checking several times, this really does look like a real deadlock.
throw new DeadlockDetectedException( message );
}
}