forked from clojure/clojure
/
LockingTransaction.java
645 lines (564 loc) · 14.2 KB
/
LockingTransaction.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
/**
* Copyright (c) Rich Hickey. All rights reserved.
* The use and distribution terms for this software are covered by the
* Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
* which can be found in the file epl-v10.html at the root of this distribution.
* By using this software in any fashion, you are agreeing to be bound by
* the terms of this license.
* You must not remove this notice, or any other, from this software.
**/
/* rich Jul 26, 2007 */
package clojure.lang;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.CountDownLatch;
@SuppressWarnings({"SynchronizeOnNonFinalField"})
public class LockingTransaction{
public static final int RETRY_LIMIT = 10000;
public static final int LOCK_WAIT_MSECS = 100;
public static final long BARGE_WAIT_NANOS = 10 * 1000000;
//public static int COMMUTE_RETRY_LIMIT = 10;
static final int RUNNING = 0;
static final int COMMITTING = 1;
static final int RETRY = 2;
static final int KILLED = 3;
static final int COMMITTED = 4;
final static ThreadLocal<LockingTransaction> transaction = new ThreadLocal<LockingTransaction>();
static class RetryEx extends Error{
}
static class AbortException extends Exception{
}
public static class Info{
final AtomicInteger status;
final long startPoint;
final CountDownLatch latch;
public Info(int status, long startPoint){
this.status = new AtomicInteger(status);
this.startPoint = startPoint;
this.latch = new CountDownLatch(1);
}
public boolean running(){
int s = status.get();
return s == RUNNING || s == COMMITTING;
}
}
static class CFn{
final IFn fn;
final ISeq args;
public CFn(IFn fn, ISeq args){
this.fn = fn;
this.args = args;
}
}
//total order on transactions
//transactions will consume a point for init, for each retry, and on commit if writing
final private static AtomicLong lastPoint = new AtomicLong();
void getReadPoint(){
readPoint = lastPoint.incrementAndGet();
}
long getCommitPoint(){
return lastPoint.incrementAndGet();
}
void stop(int status){
if(info != null)
{
synchronized(info)
{
info.status.set(status);
info.latch.countDown();
}
info = null;
vals.clear();
sets.clear();
commutes.clear();
//actions.clear();
}
}
Info info;
long readPoint;
long startPoint;
long startTime;
final RetryEx retryex = new RetryEx();
final ArrayList<Agent.Action> actions = new ArrayList<Agent.Action>();
final HashMap<Ref, Object> vals = new HashMap<Ref, Object>();
final HashSet<Ref> sets = new HashSet<Ref>();
final TreeMap<Ref, ArrayList<CFn>> commutes = new TreeMap<Ref, ArrayList<CFn>>();
final HashSet<Ref> ensures = new HashSet<Ref>(); //all hold readLock
void tryWriteLock(Ref ref){
try
{
if(!ref.lock.writeLock().tryLock(LOCK_WAIT_MSECS, TimeUnit.MILLISECONDS))
throw retryex;
}
catch(InterruptedException e)
{
throw retryex;
}
}
//returns the most recent val
Object lock(Ref ref){
//can't upgrade readLock, so release it
releaseIfEnsured(ref);
boolean unlocked = true;
try
{
tryWriteLock(ref);
unlocked = false;
if(ref.tvals != null && ref.tvals.point > readPoint)
throw retryex;
Info refinfo = ref.tinfo;
//write lock conflict
if(refinfo != null && refinfo != info && refinfo.running())
{
if(!barge(refinfo))
{
ref.lock.writeLock().unlock();
unlocked = true;
return blockAndBail(refinfo);
}
}
ref.tinfo = info;
return ref.tvals == null ? null : ref.tvals.val;
}
finally
{
if(!unlocked)
ref.lock.writeLock().unlock();
}
}
private Object blockAndBail(Info refinfo){
//stop prior to blocking
stop(RETRY);
try
{
refinfo.latch.await(LOCK_WAIT_MSECS, TimeUnit.MILLISECONDS);
}
catch(InterruptedException e)
{
//ignore
}
throw retryex;
}
private void releaseIfEnsured(Ref ref){
if(ensures.contains(ref))
{
ensures.remove(ref);
ref.lock.readLock().unlock();
}
}
void abort() throws AbortException{
stop(KILLED);
throw new AbortException();
}
private boolean bargeTimeElapsed(){
return System.nanoTime() - startTime > BARGE_WAIT_NANOS;
}
private boolean barge(Info refinfo){
boolean barged = false;
//if this transaction is older
// try to abort the other
if(bargeTimeElapsed() && startPoint < refinfo.startPoint)
{
barged = refinfo.status.compareAndSet(RUNNING, KILLED);
if(barged)
refinfo.latch.countDown();
}
return barged;
}
static LockingTransaction getEx(){
LockingTransaction t = transaction.get();
if(t == null || t.info == null)
throw new IllegalStateException("No transaction running");
return t;
}
static public boolean isRunning(){
return getRunning() != null;
}
static LockingTransaction getRunning(){
LockingTransaction t = transaction.get();
if(t == null || t.info == null)
return null;
return t;
}
static public Object runInTransaction(Callable fn) throws Exception{
LockingTransaction t = transaction.get();
if(t == null)
transaction.set(t = new LockingTransaction());
if(t.info != null)
return fn.call();
return t.run(fn);
}
static class Notify{
final public Ref ref;
final public Object oldval;
final public Object newval;
Notify(Ref ref, Object oldval, Object newval){
this.ref = ref;
this.oldval = oldval;
this.newval = newval;
}
}
Object run(Callable fn) throws Exception{
boolean done = false;
Object ret = null;
ArrayList<Ref> locked = new ArrayList<Ref>();
ArrayList<Notify> notify = new ArrayList<Notify>();
for(int i = 0; !done && i < RETRY_LIMIT; i++)
{
try
{
getReadPoint();
if(i == 0)
{
startPoint = readPoint;
startTime = System.nanoTime();
}
info = new Info(RUNNING, startPoint);
ret = fn.call();
//make sure no one has killed us before this point, and can't from now on
if(info.status.compareAndSet(RUNNING, COMMITTING))
{
for(Map.Entry<Ref, ArrayList<CFn>> e : commutes.entrySet())
{
Ref ref = e.getKey();
if(sets.contains(ref)) continue;
boolean wasEnsured = ensures.contains(ref);
//can't upgrade readLock, so release it
releaseIfEnsured(ref);
tryWriteLock(ref);
locked.add(ref);
if(wasEnsured && ref.tvals != null && ref.tvals.point > readPoint)
throw retryex;
Info refinfo = ref.tinfo;
if(refinfo != null && refinfo != info && refinfo.running())
{
if(!barge(refinfo))
throw retryex;
}
Object val = ref.tvals == null ? null : ref.tvals.val;
vals.put(ref, val);
for(CFn f : e.getValue())
{
vals.put(ref, f.fn.applyTo(RT.cons(vals.get(ref), f.args)));
}
}
for(Ref ref : sets)
{
tryWriteLock(ref);
locked.add(ref);
}
//validate and enqueue notifications
for(Map.Entry<Ref, Object> e : vals.entrySet())
{
Ref ref = e.getKey();
ref.validate(ref.getValidator(), e.getValue());
}
//at this point, all values calced, all refs to be written locked
//no more client code to be called
long msecs = System.currentTimeMillis();
long commitPoint = getCommitPoint();
for(Map.Entry<Ref, Object> e : vals.entrySet())
{
Ref ref = e.getKey();
Object oldval = ref.tvals == null ? null : ref.tvals.val;
Object newval = e.getValue();
int hcount = ref.histCount();
if(ref.tvals == null)
{
ref.tvals = new Ref.TVal(newval, commitPoint, msecs);
}
else if((ref.faults.get() > 0 && hcount < ref.maxHistory)
|| hcount < ref.minHistory)
{
ref.tvals = new Ref.TVal(newval, commitPoint, msecs, ref.tvals);
ref.faults.set(0);
}
else
{
ref.tvals = ref.tvals.next;
ref.tvals.val = newval;
ref.tvals.point = commitPoint;
ref.tvals.msecs = msecs;
}
if(ref.getWatches().count() > 0)
notify.add(new Notify(ref, oldval, newval));
}
done = true;
info.status.set(COMMITTED);
}
}
catch(RetryEx retry)
{
//eat this so we retry rather than fall out
}
finally
{
for(int k = locked.size() - 1; k >= 0; --k)
{
locked.get(k).lock.writeLock().unlock();
}
locked.clear();
for(Ref r : ensures)
{
r.lock.readLock().unlock();
}
ensures.clear();
stop(done ? COMMITTED : RETRY);
try
{
if(done) //re-dispatch out of transaction
{
for(Notify n : notify)
{
n.ref.notifyWatches(n.oldval, n.newval);
}
for(Agent.Action action : actions)
{
Agent.dispatchAction(action);
}
}
}
finally
{
notify.clear();
actions.clear();
}
}
}
if(!done)
throw new Exception("Transaction failed after reaching retry limit");
return ret;
}
public void enqueue(Agent.Action action){
actions.add(action);
}
Object doGet(Ref ref){
if(!info.running())
throw retryex;
if(vals.containsKey(ref))
return vals.get(ref);
try
{
ref.lock.readLock().lock();
if(ref.tvals == null)
throw new IllegalStateException(ref.toString() + " is unbound.");
Ref.TVal ver = ref.tvals;
do
{
if(ver.point <= readPoint)
return ver.val;
} while((ver = ver.prior) != ref.tvals);
}
finally
{
ref.lock.readLock().unlock();
}
//no version of val precedes the read point
ref.faults.incrementAndGet();
throw retryex;
}
Object doSet(Ref ref, Object val){
if(!info.running())
throw retryex;
if(commutes.containsKey(ref))
throw new IllegalStateException("Can't set after commute");
if(!sets.contains(ref))
{
sets.add(ref);
lock(ref);
}
vals.put(ref, val);
return val;
}
void doEnsure(Ref ref){
if(!info.running())
throw retryex;
if(ensures.contains(ref))
return;
ref.lock.readLock().lock();
//someone completed a write after our snapshot
if(ref.tvals != null && ref.tvals.point > readPoint) {
ref.lock.readLock().unlock();
throw retryex;
}
Info refinfo = ref.tinfo;
//writer exists
if(refinfo != null && refinfo.running())
{
ref.lock.readLock().unlock();
if(refinfo != info) //not us, ensure is doomed
{
blockAndBail(refinfo);
}
}
else
ensures.add(ref);
}
Object doCommute(Ref ref, IFn fn, ISeq args) throws Exception{
if(!info.running())
throw retryex;
if(!vals.containsKey(ref))
{
Object val = null;
try
{
ref.lock.readLock().lock();
val = ref.tvals == null ? null : ref.tvals.val;
}
finally
{
ref.lock.readLock().unlock();
}
vals.put(ref, val);
}
ArrayList<CFn> fns = commutes.get(ref);
if(fns == null)
commutes.put(ref, fns = new ArrayList<CFn>());
fns.add(new CFn(fn, args));
Object ret = fn.applyTo(RT.cons(vals.get(ref), args));
vals.put(ref, ret);
return ret;
}
/*
//for test
static CyclicBarrier barrier;
static ArrayList<Ref> items;
public static void main(String[] args){
try
{
if(args.length != 4)
System.err.println("Usage: LockingTransaction nthreads nitems niters ninstances");
int nthreads = Integer.parseInt(args[0]);
int nitems = Integer.parseInt(args[1]);
int niters = Integer.parseInt(args[2]);
int ninstances = Integer.parseInt(args[3]);
if(items == null)
{
ArrayList<Ref> temp = new ArrayList(nitems);
for(int i = 0; i < nitems; i++)
temp.add(new Ref(0));
items = temp;
}
class Incr extends AFn{
public Object invoke(Object arg1) throws Exception{
Integer i = (Integer) arg1;
return i + 1;
}
public Obj withMeta(IPersistentMap meta){
throw new UnsupportedOperationException();
}
}
class Commuter extends AFn implements Callable{
int niters;
List<Ref> items;
Incr incr;
public Commuter(int niters, List<Ref> items){
this.niters = niters;
this.items = items;
this.incr = new Incr();
}
public Object call() throws Exception{
long nanos = 0;
for(int i = 0; i < niters; i++)
{
long start = System.nanoTime();
LockingTransaction.runInTransaction(this);
nanos += System.nanoTime() - start;
}
return nanos;
}
public Object invoke() throws Exception{
for(Ref tref : items)
{
LockingTransaction.getEx().doCommute(tref, incr);
}
return null;
}
public Obj withMeta(IPersistentMap meta){
throw new UnsupportedOperationException();
}
}
class Incrementer extends AFn implements Callable{
int niters;
List<Ref> items;
public Incrementer(int niters, List<Ref> items){
this.niters = niters;
this.items = items;
}
public Object call() throws Exception{
long nanos = 0;
for(int i = 0; i < niters; i++)
{
long start = System.nanoTime();
LockingTransaction.runInTransaction(this);
nanos += System.nanoTime() - start;
}
return nanos;
}
public Object invoke() throws Exception{
for(Ref tref : items)
{
//Transaction.get().doTouch(tref);
// LockingTransaction t = LockingTransaction.getEx();
// int val = (Integer) t.doGet(tref);
// t.doSet(tref, val + 1);
int val = (Integer) tref.get();
tref.set(val + 1);
}
return null;
}
public Obj withMeta(IPersistentMap meta){
throw new UnsupportedOperationException();
}
}
ArrayList<Callable<Long>> tasks = new ArrayList(nthreads);
for(int i = 0; i < nthreads; i++)
{
ArrayList<Ref> si;
synchronized(items)
{
si = (ArrayList<Ref>) items.clone();
}
Collections.shuffle(si);
tasks.add(new Incrementer(niters, si));
//tasks.add(new Commuter(niters, si));
}
ExecutorService e = Executors.newFixedThreadPool(nthreads);
if(barrier == null)
barrier = new CyclicBarrier(ninstances);
System.out.println("waiting for other instances...");
barrier.await();
System.out.println("starting");
long start = System.nanoTime();
List<Future<Long>> results = e.invokeAll(tasks);
long estimatedTime = System.nanoTime() - start;
System.out.printf("nthreads: %d, nitems: %d, niters: %d, time: %d%n", nthreads, nitems, niters,
estimatedTime / 1000000);
e.shutdown();
for(Future<Long> result : results)
{
System.out.printf("%d, ", result.get() / 1000000);
}
System.out.println();
System.out.println("waiting for other instances...");
barrier.await();
synchronized(items)
{
for(Ref item : items)
{
System.out.printf("%d, ", (Integer) item.currentVal());
}
}
System.out.println("\ndone");
System.out.flush();
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
*/
}