-
Notifications
You must be signed in to change notification settings - Fork 470
/
Locking.java
1416 lines (1228 loc) · 49.5 KB
/
Locking.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
package org.jgroups.protocols;
import org.jgroups.*;
import org.jgroups.annotations.MBean;
import org.jgroups.annotations.ManagedAttribute;
import org.jgroups.annotations.ManagedOperation;
import org.jgroups.annotations.Property;
import org.jgroups.blocks.locking.AwaitInfo;
import org.jgroups.blocks.locking.LockInfo;
import org.jgroups.blocks.locking.LockNotification;
import org.jgroups.stack.Protocol;
import org.jgroups.util.Bits;
import org.jgroups.util.Owner;
import org.jgroups.util.Streamable;
import org.jgroups.util.Util;
import java.io.DataInput;
import java.io.DataOutput;
import java.util.*;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.LockSupport;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Supplier;
/**
* Base locking protocol, handling most of the protocol communication with other instances. To use distributed locking,
* {@link org.jgroups.blocks.locking.LockService} is placed on a channel. LockService talks to a subclass of Locking
* via events.
* @author Bela Ban
* @since 2.12
* @see org.jgroups.protocols.CENTRAL_LOCK
*/
@MBean(description="Based class for locking functionality")
abstract public class Locking extends Protocol {
@Property(description="bypasses message bundling if set")
protected boolean bypass_bundling=true;
@Property(description="Number of locks to be used for lock striping (for synchronized access to the server_lock entries)")
protected int lock_striping_size=10;
protected Address local_addr;
protected View view;
// server side locks
protected final ConcurrentMap<String,ServerLock> server_locks=Util.createConcurrentMap(20);
// protected access to the same locks in server_locks
protected Lock[] lock_stripes;
// client side locks
protected final ClientLockTable client_lock_table=new ClientLockTable();
protected final Set<LockNotification> lock_listeners=new CopyOnWriteArraySet<>();
protected final static AtomicInteger current_lock_id=new AtomicInteger(1);
protected enum Type {
GRANT_LOCK, // request to acquire a lock
LOCK_GRANTED, // response to sender of GRANT_LOCK on succcessful lock acquisition
LOCK_DENIED, // response to sender of GRANT_LOCK on unsuccessful lock acquisition (e.g. on tryLock())
RELEASE_LOCK, // request to release a lock
CREATE_LOCK, // request to create a server lock (sent by coordinator to backups). Used by CentralLockService
DELETE_LOCK, // request to delete a server lock (sent by coordinator to backups). Used by CentralLockService
LOCK_AWAIT, // request to await until condition is signaled
COND_SIG, // request to signal awaiting thread
COND_SIG_ALL, // request to signal all awaiting threads
SIG_RET, // response to alert of signal
DELETE_LOCK_AWAIT, // request to delete a waiter
CREATE_AWAITER, // request to create a server lock await (sent by coordinator to backups). Used by CentralLockService
DELETE_AWAITER // request to delete a server lock await (sent by coordinator to backups). Used by CentralLockService
}
public Locking() {
}
public boolean getBypassBundling() {
return bypass_bundling;
}
public void setBypassBundling(boolean bypass_bundling) {
this.bypass_bundling=bypass_bundling;
}
public void addLockListener(LockNotification listener) {
if(listener != null)
lock_listeners.add(listener);
}
public void removeLockListener(LockNotification listener) {
if(listener != null)
lock_listeners.remove(listener);
}
@ManagedAttribute
public String getAddress() {
return local_addr != null? local_addr.toString() : null;
}
@ManagedAttribute
public String getView() {
return view != null? view.toString() : null;
}
public void init() throws Exception {
super.init();
lock_stripes=new Lock[lock_striping_size];
for(int i=0; i < lock_stripes.length; i++)
lock_stripes[i]=new ReentrantLock();
}
public Object down(Event evt) {
switch(evt.getType()) {
case Event.LOCK:
LockInfo info=evt.getArg();
ClientLock lock=getLock(info.getName());
if(!info.isTrylock()) {
if(info.isLockInterruptibly()) {
try {
lock.lockInterruptibly();
}
catch(InterruptedException e) {
Thread.currentThread().interrupt(); // has to be checked by caller who has to rethrow ...
}
}
else
lock.lock();
}
else {
if(info.isUseTimeout()) {
try {
return lock.tryLock(info.getTimeout(), info.getTimeUnit());
}
catch(InterruptedException e) {
Thread.currentThread().interrupt();
}
}
else
return lock.tryLock();
}
return null;
case Event.UNLOCK:
info=evt.getArg();
lock=getLock(info.getName(), false);
if(lock != null)
lock.unlock();
return null;
case Event.UNLOCK_ALL:
unlockAll();
return null;
case Event.LOCK_AWAIT:
info=evt.getArg();
lock=getLock(info.getName(), false);
if (lock == null || !lock.acquired) {
throw new IllegalMonitorStateException();
}
Condition condition = lock.newCondition();
if (info.isUseTimeout()) {
try {
return condition.awaitNanos(info.getTimeUnit().toNanos(info.getTimeout()));
}
catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
else if (info.isLockInterruptibly()) {
try {
condition.await();
}
catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
else {
condition.awaitUninterruptibly();
}
return null;
case Event.LOCK_SIGNAL:
AwaitInfo awaitInfo =evt.getArg();
lock=getLock(awaitInfo.getName(), false);
if (lock == null || !lock.acquired) {
throw new IllegalMonitorStateException();
}
sendSignalConditionRequest(awaitInfo.getName(), awaitInfo.isAll());
return null;
case Event.SET_LOCAL_ADDRESS:
local_addr=evt.getArg();
break;
case Event.VIEW_CHANGE:
handleView(evt.getArg());
break;
}
return down_prot.down(evt);
}
public Object up(Event evt) {
switch(evt.getType()) {
case Event.VIEW_CHANGE:
handleView(evt.getArg());
break;
}
return up_prot.up(evt);
}
public Object up(Message msg) {
LockingHeader hdr=msg.getHeader(id);
if(hdr == null)
return up_prot.up(msg);
if (null != view && !view.containsMember(msg.getSrc())) {
log.error("Received locking event from '%s' but member is not present in the current view - ignoring request", msg.src());
return null;
}
Request req=null;
try {
req=Util.streamableFromBuffer(Request.class, msg.getRawBuffer(), msg.getOffset(), msg.getLength());
}
catch(Exception ex) {
log.error("failed deserializng request", ex);
return null;
}
log.trace("[%s] <-- [%s] %s", local_addr, msg.getSrc(), req);
switch(req.type) {
case GRANT_LOCK:
case RELEASE_LOCK:
handleLockRequest(req);
break;
case LOCK_GRANTED:
handleLockGrantedResponse(req.lock_name, req.lock_id, req.owner);
break;
case LOCK_DENIED:
handleLockDeniedResponse(req.lock_name, req.lock_id, req.owner);
break;
case CREATE_LOCK:
handleCreateLockRequest(req.lock_name, req.owner);
break;
case DELETE_LOCK:
handleDeleteLockRequest(req.lock_name);
break;
case COND_SIG:
case COND_SIG_ALL:
handleSignalRequest(req);
break;
case LOCK_AWAIT:
handleAwaitRequest(req.lock_name, req.owner);
handleLockRequest(req);
break;
case DELETE_LOCK_AWAIT:
handleDeleteAwaitRequest(req.lock_name, req.owner);
break;
case SIG_RET:
handleSignalResponse(req.lock_name, req.owner);
break;
case CREATE_AWAITER:
handleCreateAwaitingRequest(req.lock_name, req.owner);
break;
case DELETE_AWAITER:
handleDeleteAwaitingRequest(req.lock_name, req.owner);
break;
default:
log.error("Request of type %s not known", req.type);
break;
}
return null;
}
protected ClientLock getLock(String name) {
return client_lock_table.getLock(name,getOwner(),true);
}
protected ClientLock getLock(String name, boolean create_if_absent) {
return client_lock_table.getLock(name,getOwner(),create_if_absent);
}
@ManagedOperation(description="Unlocks all currently held locks")
public void unlockAll() {
client_lock_table.unlockAll();
}
@ManagedOperation(description="Dumps all locks")
public String printLocks() {
StringBuilder sb=new StringBuilder();
sb.append("server locks:\n");
for(Map.Entry<String,ServerLock> entry: server_locks.entrySet())
sb.append(entry.getKey()).append(": ").append(entry.getValue()).append("\n");
sb.append("\nmy locks: ").append(client_lock_table.toString());
return sb.toString();
}
protected void handleView(View view) {
this.view=view;
log.debug("view=%s", view);
List<Address> members=view.getMembers();
List<Response> responses=new ArrayList<>();
for(Map.Entry<String,ServerLock> entry: server_locks.entrySet()) {
String lock_name=entry.getKey();
ServerLock server_lock=entry.getValue();
Lock lock=_getLock(lock_name);
lock.lock();
try {
Response rsp=server_lock.handleView(members);
if(rsp != null)
responses.add(rsp);
if(server_lock.isEmpty() && server_lock.current_owner == null && server_lock.condition.queue.isEmpty())
server_locks.remove(lock_name);
}
finally {
lock.unlock();
}
}
// do the sending outside the lock scope (might block on credits or TCP send)
for(Response rsp: responses)
sendLockResponse(rsp.type, rsp.owner, rsp.lock_name, rsp.lock_id);
}
protected ClientLock createLock(String lock_name, Owner owner) {
return new ClientLock(lock_name, owner);
}
/** Gets a lock from locks based on the hash of the lock name */
protected Lock _getLock(String lock_name) {
int index=lock_name != null? Math.abs(lock_name.hashCode() % lock_stripes.length) : 0;
return lock_stripes[index];
}
protected Owner getOwner() {
return new Owner(local_addr, Thread.currentThread().getId());
}
abstract protected void sendGrantLockRequest(String lock_name, int lock_id, Owner owner, long timeout, boolean is_trylock);
abstract protected void sendReleaseLockRequest(String lock_name, Owner owner);
abstract protected void sendAwaitConditionRequest(String lock_name, Owner owner);
abstract protected void sendSignalConditionRequest(String lock_name, boolean all);
abstract protected void sendDeleteAwaitConditionRequest(String lock_name, Owner owner);
protected void sendRequest(Address dest, Type type, String lock_name, Owner owner, long timeout, boolean is_trylock) {
send(dest, new Request(type, lock_name, owner, timeout, is_trylock));
}
protected void sendRequest(Address dest, Type type, String lock_name, int lock_id, Owner owner, long timeout, boolean is_trylock) {
send(dest, new Request(type, lock_name, owner, timeout, is_trylock).lockId(lock_id));
}
protected void sendLockResponse(Type type, Owner dest, String lock_name, int lock_id) {
send(dest.getAddress(), new Request(type, lock_name, dest, 0).lockId(lock_id));
}
protected void sendSignalResponse(Owner dest, String lock_name) {
send(dest.getAddress(), new Request(Type.SIG_RET, lock_name, dest, 0));
}
protected void send(Address dest, Request req) {
Message msg=new Message(dest, Util.streamableToBuffer(req)).putHeader(id, new LockingHeader());
if(bypass_bundling)
msg.setFlag(Message.Flag.DONT_BUNDLE);
log.trace("[%s] --> %s] %s", local_addr, dest == null? "ALL" : dest, req);
try {
down_prot.down(msg);
}
catch(Exception ex) {
log.error("failed sending %s request: %s", req.type, ex);
}
}
protected void handleLockRequest(Request req) {
Response rsp=null;
Lock lock=_getLock(req.lock_name);
lock.lock();
try {
ServerLock server_lock=server_locks.get(req.lock_name);
if(server_lock == null) {
server_lock=new ServerLock(req.lock_name);
ServerLock tmp=server_locks.putIfAbsent(req.lock_name, server_lock);
if(tmp != null)
server_lock=tmp;
else
notifyLockCreated(req.lock_name);
}
rsp=server_lock.handleRequest(req);
if(server_lock.isEmpty() && server_lock.current_owner == null && server_lock.condition.queue.isEmpty())
server_locks.remove(req.lock_name);
}
finally {
lock.unlock();
}
// moved outside the lock scope
if(rsp != null)
sendLockResponse(rsp.type, rsp.owner, rsp.lock_name, rsp.lock_id);
}
protected void handleLockGrantedResponse(String lock_name, int lock_id, Owner owner) {
ClientLock lock=client_lock_table.getLock(lock_name,owner,false);
if(lock != null)
lock.handleLockGrantedResponse(lock_id);
}
protected void handleLockDeniedResponse(String lock_name, int lock_id, Owner owner) {
ClientLock lock=client_lock_table.getLock(lock_name,owner,false);
if(lock != null)
lock.lockDenied(lock_id);
}
protected void handleAwaitRequest(String lock_name, Owner owner) {
Lock lock=_getLock(lock_name);
lock.lock();
try {
ServerLock server_lock=server_locks.get(lock_name);
if (server_lock != null)
server_lock.condition.addWaiter(owner);
else
log.error(Util.getMessage("ConditionAwaitWasReceivedButLockWasNotCreatedWaiterMayBlockForever"));
}
finally {
lock.unlock();
}
}
protected void handleDeleteAwaitRequest(String lock_name, Owner owner) {
Lock lock=_getLock(lock_name);
lock.lock();
try {
ServerLock server_lock=server_locks.get(lock_name);
if (server_lock != null)
server_lock.condition.removeWaiter(owner);
else
log.error(Util.getMessage("ConditionAwaitDeleteWasReceivedButLockWasGone"));
}
finally {
lock.unlock();
}
}
protected void handleSignalResponse(String lock_name, Owner owner) {
ClientLock lock=client_lock_table.getLock(lock_name,owner,false);
if(lock != null) {
lock.condition.signaled();
}
else {
log.error(Util.getMessage("ConditionResponseWasClientLockWasNotPresentIgnoredSignal"));
}
}
protected void handleSignalRequest(Request req) {
Response rsp=null;
Lock lock=_getLock(req.lock_name);
lock.lock();
try {
ServerLock server_lock=server_locks.get(req.lock_name);
if (server_lock != null)
rsp=server_lock.handleRequest(req);
else
log.error(Util.getMessage("ConditionSignalWasReceivedButLockWasNotCreatedCouldnTNotifyAnyone"));
}
finally {
lock.unlock();
}
// moved outside the lock scope
if(rsp != null)
sendLockResponse(rsp.type, rsp.owner, rsp.lock_name, rsp.lock_id);
}
protected void handleCreateLockRequest(String lock_name, Owner owner) {
Lock lock=_getLock(lock_name);
lock.lock();
try {
server_locks.put(lock_name, new ServerLock(lock_name, owner));
}
finally {
lock.unlock();
}
}
protected void handleDeleteLockRequest(String lock_name) {
Lock lock=_getLock(lock_name);
lock.lock();
try {
ServerLock server_lock = server_locks.get(lock_name);
if(server_lock == null)
return;
if (server_lock.condition.queue.isEmpty())
server_locks.remove(lock_name);
else
server_lock.current_owner = null;
}
finally {
lock.unlock();
}
}
protected void handleCreateAwaitingRequest(String lock_name, Owner owner) {
Lock lock=_getLock(lock_name);
lock.lock();
try {
ServerLock server_lock = server_locks.get(lock_name);
if (server_lock == null) {
server_lock = new ServerLock(lock_name);
ServerLock tmp=server_locks.putIfAbsent(lock_name,server_lock);
if(tmp != null)
server_lock=tmp;
}
server_lock.condition.queue.add(owner);
}
finally {
lock.unlock();
}
}
protected void handleDeleteAwaitingRequest(String lock_name, Owner owner) {
Lock lock=_getLock(lock_name);
lock.lock();
try {
ServerLock server_lock = server_locks.get(lock_name);
if (server_lock != null) {
server_lock.condition.queue.remove(owner);
if (server_lock.condition.queue.isEmpty() && server_lock.current_owner == null) {
server_locks.remove(lock_name);
}
}
}
finally {
lock.unlock();
}
}
protected void notifyLockCreated(String lock_name) {
for(LockNotification listener: lock_listeners) {
try {
listener.lockCreated(lock_name);
}
catch(Throwable t) {
log.error("failed notifying %s: %s", listener, t.toString());
}
}
}
protected void notifyLockDeleted(String lock_name) {
for(LockNotification listener: lock_listeners) {
try {
listener.lockDeleted(lock_name);
}
catch(Throwable t) {
log.error("failed notifying %s: %s", listener, t.toString());
}
}
}
protected void notifyLocked(String lock_name, Owner owner) {
for(LockNotification listener: lock_listeners) {
try {
listener.locked(lock_name,owner);
}
catch(Throwable t) {
log.error("failed notifying %s: %s", listener, t.toString());
}
}
}
protected void notifyUnlocked(String lock_name, Owner owner) {
for(LockNotification listener: lock_listeners) {
try {
listener.unlocked(lock_name,owner);
}
catch(Throwable t) {
log.error("failed notifying %s: %s", listener, t.toString());
}
}
}
protected void notifyAwaiting(String lock_name, Owner owner) {
for(LockNotification listener: lock_listeners) {
try {
listener.awaiting(lock_name,owner);
}
catch(Throwable t) {
log.error("failed notifying %s: %s", listener, t.toString());
}
}
}
protected void notifyAwaited(String lock_name, Owner owner) {
for(LockNotification listener: lock_listeners) {
try {
listener.awaited(lock_name,owner);
}
catch(Throwable t) {
log.error("failed notifying %s: %s", listener, t.toString());
}
}
}
/**
* Server side queue for handling of lock requests (lock, release).
* @author Bela Ban
*/
protected class ServerLock {
protected final String lock_name;
protected Owner current_owner;
protected final List<Request> queue=new ArrayList<>();
protected final ServerCondition condition;
public ServerLock(String lock_name) {
this.lock_name=lock_name;
this.condition=new ServerCondition(this);
}
protected ServerLock(String lock_name, Owner owner) {
this.lock_name=lock_name;
this.current_owner=owner;
this.condition=new ServerCondition(this);
}
protected Response handleRequest(Request req) {
switch(req.type) {
case GRANT_LOCK:
if(current_owner == null) {
setOwner(req.owner);
return new Response(Type.LOCK_GRANTED, req.owner, req.lock_name, req.lock_id);
}
if(current_owner.equals(req.owner))
return new Response(Type.LOCK_GRANTED, req.owner, req.lock_name, req.lock_id);
if(req.is_trylock && req.timeout <= 0)
return new Response(Type.LOCK_DENIED, req.owner, req.lock_name, req.lock_id);
addToQueue(req);
break;
case RELEASE_LOCK:
case LOCK_AWAIT:
if(current_owner == null)
break;
if(current_owner.equals(req.owner))
setOwner(null);
else
addToQueue(req);
break;
case COND_SIG:
condition.signal(false);
break;
case COND_SIG_ALL:
condition.signal(true);
break;
default:
throw new IllegalArgumentException("type " + req.type + " is invalid here");
}
return processQueue();
}
protected Response handleView(List<Address> members) {
if(current_owner != null && !members.contains(current_owner.getAddress())) {
Owner tmp=current_owner;
setOwner(null);
log.debug("unlocked \"%s\" because owner %s left", lock_name, tmp);
}
synchronized(queue) {
for(Iterator<Request> it=queue.iterator(); it.hasNext(); ) {
Request req=it.next();
if(!members.contains(req.owner.getAddress()))
it.remove();
}
}
for(Iterator<Owner> it=condition.queue.iterator(); it.hasNext();) {
Owner own=it.next();
if(!members.contains(own.getAddress()))
it.remove();
}
return processQueue();
}
protected void addToQueue(Request req) {
synchronized(queue) {
if(queue.isEmpty()) {
if(req.type == Type.GRANT_LOCK)
queue.add(req);
return; // RELEASE_LOCK is discarded on an empty queue
}
}
// at this point the queue is not empty
switch(req.type) {
// If there is already a lock request from the same owner, discard the new lock request
case GRANT_LOCK:
synchronized(queue) {
if(!isRequestPresent(Type.GRANT_LOCK, req.owner))
queue.add(req);
}
break;
case RELEASE_LOCK:
// Release the lock request from the same owner already in the queue
// If there is no lock request, discard the unlock request
removeRequest(Type.GRANT_LOCK, req.owner);
break;
}
}
/** Checks if a certain request from a given owner is already in the queue */
protected boolean isRequestPresent(Type type, Owner owner) { // holds lock on queue
for(Request req: queue)
if(req.type == type && req.owner.equals(owner))
return true;
return false;
}
protected void removeRequest(Type type, Owner owner) {
synchronized(queue) {
for(Iterator<Request> it=queue.iterator(); it.hasNext(); ) {
Request req=it.next();
if(req.type == type && req.owner.equals(owner))
it.remove();
}
}
}
protected Request getNextRequest() {
synchronized(queue) {
return !queue.isEmpty()? queue.remove(0) : null;
}
}
protected Response processQueue() {
if(current_owner != null)
return null;
Request req;
while((req=getNextRequest()) != null) {
if(req.type == Type.GRANT_LOCK) {
setOwner(req.owner);
return new Response(Type.LOCK_GRANTED, req.owner, req.lock_name, req.lock_id);
}
}
return null;
}
protected void setOwner(Owner owner) {
if(owner == null) {
if(current_owner != null) {
Owner tmp=current_owner;
current_owner=null;
notifyUnlocked(lock_name, tmp);
}
}
else {
current_owner=owner;
notifyLocked(lock_name, owner);
}
}
public boolean isEmpty() {
synchronized(queue) {
return queue.isEmpty();
}
}
public String toString() {
StringBuilder sb=new StringBuilder();
sb.append(current_owner);
synchronized(queue) {
if(!queue.isEmpty()) {
sb.append(", queue: ");
for(Request req : queue) {
sb.append(req.toStringShort()).append(" ");
}
}
}
return sb.toString();
}
}
protected class ServerCondition {
protected final ServerLock lock;
protected final Queue<Owner> queue=new ArrayDeque<>();
public ServerCondition(ServerLock lock) {
this.lock = lock;
}
public void addWaiter(Owner waiter) {
notifyAwaiting(lock.lock_name, waiter);
log.trace("Waiter [%s] was added for %s", waiter, lock.lock_name);
queue.add(waiter);
}
public void removeWaiter(Owner waiter) {
notifyAwaited(lock.lock_name, waiter);
log.trace("Waiter [%s] was removed for %s", waiter, lock.lock_name);
queue.remove(waiter);
}
public void signal(boolean all) {
if (queue.isEmpty())
log.trace("Signal for [%s] ignored since, no one is waiting in queue", lock.lock_name);
Owner entry;
if (all) {
while ((entry = queue.poll()) != null) {
notifyAwaited(lock.lock_name, entry);
log.trace("Signalled %s for %s", entry, lock.lock_name);
sendSignalResponse(entry, lock.lock_name);
}
}
else {
entry = queue.poll();
if (entry != null) {
notifyAwaited(lock.lock_name, entry);
log.trace("Signalled %s for %s", entry, lock.lock_name);
sendSignalResponse(entry, lock.lock_name);
}
}
}
}
/**
* Implementation of {@link Lock}. This is a client stub communicates with a server equivalent. The semantics are
* more or less those of {@link Lock}, but may differ slightly.
* For details see {@link org.jgroups.blocks.locking.LockService}.
*/
protected class ClientLock implements Lock {
protected final String name;
protected Owner owner;
protected volatile boolean acquired;
protected volatile boolean denied;
protected volatile boolean is_trylock;
protected long timeout;
protected final ClientCondition condition;
// unique for locks for the same name:owner, can wrap around (that's ok)
protected final int lock_id=current_lock_id.getAndIncrement();
public ClientLock(String name) {
this.name=name;
this.condition = new ClientCondition(this);
}
public ClientLock(String name, Owner owner) {
this(name);
this.owner=owner;
}
public void lock() {
try {
acquire(false);
}
catch(InterruptedException e) { // should never happen
Thread.currentThread().interrupt(); // just a second line of defense
}
}
public void lockInterruptibly() throws InterruptedException {
acquire(true);
}
public boolean tryLock() {
try {
return acquireTryLock(0, false);
}
catch(InterruptedException e) {
Thread.currentThread().interrupt();
return false;
}
}
public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
return acquireTryLock(TimeUnit.MILLISECONDS.convert(time, unit), true);
}
public synchronized void unlock() {
_unlock(false);
}
public Condition newCondition() {
// Currently only 1 condition per Lock is supported
return condition;
}
public String toString() {
return name + " (id=" + lock_id + ", locked=" + acquired + ")";
}
protected synchronized void lockGranted(int lock_id) {
if(this.lock_id != lock_id) {
log.error(Util.getMessage("DiscardedLOCKGRANTEDResponseWithLockId") + lock_id + ", my lock-id=" + this.lock_id);
return;
}
acquired=true;
this.notifyAll();
}
protected synchronized void lockDenied(int lock_id) {
if(this.lock_id != lock_id) {
log.error(Util.getMessage("DiscardedLOCKDENIEDResponseWithLockId") + lock_id + ", my lock_id=" + this.lock_id);
return;
}
denied=true;
this.notifyAll();
}
protected void handleLockGrantedResponse(int lock_id) {
lockGranted(lock_id);
}
protected synchronized void acquire(boolean throwInterrupt) throws InterruptedException {
if(acquired)
return;
if(throwInterrupt && Thread.interrupted())
throw new InterruptedException();
owner=getOwner();
sendGrantLockRequest(name, lock_id, owner, 0, false);
boolean interrupted=false;
while(!acquired) {
try {
this.wait();
}
catch(InterruptedException e) {
if(throwInterrupt && !acquired) {
_unlock(true);
throw e;
}
// If we don't throw exceptions then we just set the interrupt flag and let it loop around
interrupted=true;
}
}
if(interrupted)
Thread.currentThread().interrupt();
}
protected synchronized void _unlock(boolean force) {
if(!acquired && !denied && !force)
return;
this.timeout=0;
this.is_trylock=false;
if(!denied)
sendReleaseLockRequest(name, owner);
acquired=denied=false;
notifyAll();
client_lock_table.removeClientLock(name,owner);
notifyLockDeleted(name);
owner=null;
}
protected synchronized boolean acquireTryLock(long timeout, boolean use_timeout) throws InterruptedException {
if(denied)
return false;
if(!acquired) {
if(use_timeout && Thread.interrupted())
throw new InterruptedException();
is_trylock=true;
this.timeout=timeout;
if(owner == null)
owner=getOwner();
sendGrantLockRequest(name, lock_id, owner, timeout, true);
boolean interrupted = false;
while(!acquired && !denied) {
if(use_timeout) {
long timeout_ns=TimeUnit.NANOSECONDS.convert(timeout, TimeUnit.MILLISECONDS),