/
AbstractIoFuture.java
726 lines (611 loc) · 21.9 KB
/
AbstractIoFuture.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
/*
* JBoss, Home of Professional Open Source
*
* Copyright 2008 Red Hat, Inc. and/or its affiliates.
*
* Licensed 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.xnio;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.CancellationException;
import java.util.concurrent.Executor;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.LockSupport;
import static org.xnio._private.Messages.futureMsg;
/**
* An abstract base class for {@code IoFuture} objects. Used to easily produce implementations.
*
* @param <T> the type of result that this operation produces
*/
public abstract class AbstractIoFuture<T> implements IoFuture<T> {
@SuppressWarnings("unchecked")
private final AtomicReference<State<T>> stateRef = new AtomicReference<>((State<T>) ST_INITIAL);
private static final State<?> ST_INITIAL = new InitialState<>();
private static final State<?> ST_CANCELLED = new CancelledState<>();
static abstract class State<T> {
abstract Status getStatus();
abstract void notifyDone(AbstractIoFuture<T> future, T result);
abstract void notifyFailed(AbstractIoFuture<T> future, IOException exception);
abstract void notifyCancelled(AbstractIoFuture<T> future);
abstract void cancel();
abstract boolean cancelRequested();
State<T> withWaiter(final Thread thread) {
return new WaiterState<T>(this, thread);
}
<A> State<T> withNotifier(final Executor executor, final AbstractIoFuture<T> future, final Notifier<? super T, A> notifier, final A attachment) {
return new NotifierState<T, A>(this, notifier, attachment);
}
State<T> withCancelHandler(final Cancellable cancellable) {
return new CancellableState<T>(this, cancellable);
}
T getResult() {
throw new IllegalStateException();
}
IOException getException() {
throw new IllegalStateException();
}
}
static final class InitialState<T> extends State<T> {
Status getStatus() {
return Status.WAITING;
}
void notifyDone(final AbstractIoFuture<T> future, final T result) {
}
void notifyFailed(final AbstractIoFuture<T> future, final IOException exception) {
}
void notifyCancelled(final AbstractIoFuture<T> future) {
}
void cancel() {
}
boolean cancelRequested() {
return false;
}
}
static final class CompleteState<T> extends State<T> {
private final T result;
CompleteState(final T result) {
this.result = result;
}
Status getStatus() {
return Status.DONE;
}
void notifyDone(final AbstractIoFuture<T> future, final T result) {
}
void notifyFailed(final AbstractIoFuture<T> future, final IOException exception) {
}
void notifyCancelled(final AbstractIoFuture<T> future) {
}
void cancel() {
}
State<T> withCancelHandler(final Cancellable cancellable) {
return this;
}
State<T> withWaiter(final Thread thread) {
return this;
}
<A> State<T> withNotifier(final Executor executor, final AbstractIoFuture<T> future, final Notifier<? super T, A> notifier, final A attachment) {
future.runNotifier(new NotifierRunnable<T, A>(notifier, future, attachment));
return this;
}
T getResult() {
return result;
}
boolean cancelRequested() {
return false;
}
}
static final class FailedState<T> extends State<T> {
private final IOException exception;
FailedState(final IOException exception) {
this.exception = exception;
}
Status getStatus() {
return Status.FAILED;
}
void notifyDone(final AbstractIoFuture<T> future, final T result) {
}
void notifyFailed(final AbstractIoFuture<T> future, final IOException exception) {
}
void notifyCancelled(final AbstractIoFuture<T> future) {
}
void cancel() {
}
State<T> withCancelHandler(final Cancellable cancellable) {
return this;
}
State<T> withWaiter(final Thread thread) {
return this;
}
<A> State<T> withNotifier(final Executor executor, final AbstractIoFuture<T> future, final Notifier<? super T, A> notifier, final A attachment) {
future.runNotifier(new NotifierRunnable<T, A>(notifier, future, attachment));
return this;
}
IOException getException() {
return exception;
}
boolean cancelRequested() {
return false;
}
}
static final class CancelledState<T> extends State<T> {
CancelledState() {
}
Status getStatus() {
return Status.CANCELLED;
}
void notifyDone(final AbstractIoFuture<T> future, final T result) {
}
void notifyFailed(final AbstractIoFuture<T> future, final IOException exception) {
}
void notifyCancelled(final AbstractIoFuture<T> future) {
}
void cancel() {
}
State<T> withCancelHandler(final Cancellable cancellable) {
try {
cancellable.cancel();
} catch (Throwable ignored) {}
return this;
}
<A> State<T> withNotifier(final Executor executor, final AbstractIoFuture<T> future, final Notifier<? super T, A> notifier, final A attachment) {
future.runNotifier(new NotifierRunnable<T, A>(notifier, future, attachment));
return this;
}
State<T> withWaiter(final Thread thread) {
return this;
}
boolean cancelRequested() {
return true;
}
}
static final class NotifierState<T, A> extends State<T> {
final State<T> next;
final Notifier<? super T, A> notifier;
final A attachment;
NotifierState(final State<T> next, final Notifier<? super T, A> notifier, final A attachment) {
this.next = next;
this.notifier = notifier;
this.attachment = attachment;
}
Status getStatus() {
return Status.WAITING;
}
void notifyDone(final AbstractIoFuture<T> future, final T result) {
doNotify(future);
next.notifyDone(future, result);
}
void notifyFailed(final AbstractIoFuture<T> future, final IOException exception) {
doNotify(future);
next.notifyFailed(future, exception);
}
void notifyCancelled(final AbstractIoFuture<T> future) {
doNotify(future);
next.notifyCancelled(future);
}
void cancel() {
next.cancel();
}
private void doNotify(final AbstractIoFuture<T> future) {
future.runNotifier(new NotifierRunnable<T, A>(notifier, future, attachment));
}
boolean cancelRequested() {
return next.cancelRequested();
}
}
static final class WaiterState<T> extends State<T> {
final State<T> next;
final Thread waiter;
WaiterState(final State<T> next, final Thread waiter) {
this.next = next;
this.waiter = waiter;
}
Status getStatus() {
return Status.WAITING;
}
void notifyDone(final AbstractIoFuture<T> future, final T result) {
LockSupport.unpark(waiter);
next.notifyDone(future, result);
}
void notifyFailed(final AbstractIoFuture<T> future, final IOException exception) {
LockSupport.unpark(waiter);
next.notifyFailed(future, exception);
}
void notifyCancelled(final AbstractIoFuture<T> future) {
LockSupport.unpark(waiter);
next.notifyCancelled(future);
}
void cancel() {
next.cancel();
}
boolean cancelRequested() {
return next.cancelRequested();
}
}
static final class CancellableState<T> extends State<T> {
final State<T> next;
final Cancellable cancellable;
CancellableState(final State<T> next, final Cancellable cancellable) {
this.next = next;
this.cancellable = cancellable;
}
Status getStatus() {
return Status.WAITING;
}
void notifyDone(final AbstractIoFuture<T> future, final T result) {
next.notifyDone(future, result);
}
void notifyFailed(final AbstractIoFuture<T> future, final IOException exception) {
next.notifyFailed(future, exception);
}
void notifyCancelled(final AbstractIoFuture<T> future) {
next.notifyCancelled(future);
}
void cancel() {
try {
cancellable.cancel();
} catch (Throwable ignored) {}
next.cancel();
}
boolean cancelRequested() {
return next.cancelRequested();
}
}
static final class CancelRequestedState<T> extends State<T> {
final State<T> next;
CancelRequestedState(final State<T> next) {
this.next = next;
}
Status getStatus() {
return Status.WAITING;
}
void notifyDone(final AbstractIoFuture<T> future, final T result) {
next.notifyDone(future, result);
}
void notifyFailed(final AbstractIoFuture<T> future, final IOException exception) {
next.notifyFailed(future, exception);
}
void notifyCancelled(final AbstractIoFuture<T> future) {
next.notifyCancelled(future);
}
void cancel() {
// terminate
}
boolean cancelRequested() {
return true;
}
}
/**
* Construct a new instance.
*/
protected AbstractIoFuture() {
}
/**
* {@inheritDoc}
*/
public Status getStatus() {
return getState().getStatus();
}
private State<T> getState() {
return stateRef.get();
}
private boolean compareAndSetState(State<T> expect, State<T> update) {
return stateRef.compareAndSet(expect, update);
}
/**
* {@inheritDoc}
*/
public Status await() {
final Thread thread = Thread.currentThread();
State<T> state;
for (;;) {
state = getState();
if (state.getStatus() != Status.WAITING) {
return state.getStatus();
}
Xnio.checkBlockingAllowed();
State<T> withWaiter = state.withWaiter(thread);
if (compareAndSetState(state, withWaiter)) {
boolean intr = Thread.interrupted();
try {
do {
LockSupport.park(this);
if (Thread.interrupted()) intr = true;
state = getState();
} while (state.getStatus() == Status.WAITING);
return state.getStatus();
} finally {
if (intr) thread.interrupt();
}
}
// retry
}
}
/**
* {@inheritDoc}
*/
public Status await(long time, final TimeUnit timeUnit) {
if (time < 0L) {
time = 0L;
}
long duration = timeUnit.toNanos(time);
long now = System.nanoTime();
long tick;
final Thread thread = Thread.currentThread();
State<T> state;
for (;;) {
state = getState();
if (state.getStatus() != Status.WAITING || duration == 0L) {
return state.getStatus();
}
Xnio.checkBlockingAllowed();
State<T> withWaiter = state.withWaiter(thread);
if (compareAndSetState(state, withWaiter)) {
boolean intr = Thread.interrupted();
try {
do {
LockSupport.parkNanos(this, duration);
if (Thread.interrupted()) intr = true;
state = getState();
duration -= (tick = System.nanoTime()) - now;
now = tick;
} while (state.getStatus() == Status.WAITING && duration > 0L);
return state.getStatus();
} finally {
if (intr) thread.interrupt();
}
}
// retry
}
}
/**
* {@inheritDoc}
*/
public Status awaitInterruptibly() throws InterruptedException {
final Thread thread = Thread.currentThread();
State<T> state;
for (;;) {
state = getState();
if (state.getStatus() != Status.WAITING) {
return state.getStatus();
}
Xnio.checkBlockingAllowed();
if (Thread.interrupted()) throw new InterruptedException();
State<T> withWaiter = state.withWaiter(thread);
if (compareAndSetState(state, withWaiter)) {
do {
LockSupport.park(this);
if (Thread.interrupted()) throw new InterruptedException();
state = getState();
} while (state.getStatus() == Status.WAITING);
return state.getStatus();
}
// retry
}
}
/**
* {@inheritDoc}
*/
public Status awaitInterruptibly(long time, final TimeUnit timeUnit) throws InterruptedException {
if (time < 0L) {
time = 0L;
}
long duration = timeUnit.toNanos(time);
long now = System.nanoTime();
long tick;
final Thread thread = Thread.currentThread();
State<T> state;
for (;;) {
state = getState();
if (state.getStatus() != Status.WAITING || duration == 0L) {
return state.getStatus();
}
Xnio.checkBlockingAllowed();
if (Thread.interrupted()) throw new InterruptedException();
State<T> withWaiter = state.withWaiter(thread);
if (compareAndSetState(state, withWaiter)) {
do {
LockSupport.parkNanos(this, duration);
if (Thread.interrupted()) throw new InterruptedException();
state = getState();
duration -= (tick = System.nanoTime()) - now;
now = tick;
} while (state.getStatus() == Status.WAITING && duration > 0L);
return state.getStatus();
}
// retry
}
}
/**
* {@inheritDoc}
*/
@SuppressWarnings({"unchecked"})
public T get() throws IOException, CancellationException {
switch (await()) {
case DONE: return getState().getResult();
case FAILED: throw getState().getException();
case CANCELLED: throw futureMsg.opCancelled();
default: throw new IllegalStateException();
}
}
/**
* {@inheritDoc}
*/
@SuppressWarnings({"unchecked"})
public T getInterruptibly() throws IOException, InterruptedException, CancellationException {
switch (awaitInterruptibly()) {
case DONE: return getState().getResult();
case FAILED: throw getState().getException();
case CANCELLED: throw futureMsg.opCancelled();
default: throw new IllegalStateException();
}
}
/**
* {@inheritDoc}
*/
public IOException getException() throws IllegalStateException {
return getState().getException();
}
/**
* {@inheritDoc}
*/
public <A> IoFuture<T> addNotifier(final Notifier<? super T, A> notifier, final A attachment) {
State<T> oldState, newState;
do {
oldState = getState();
newState = oldState.withNotifier(getNotifierExecutor(), this, notifier, attachment);
} while (! compareAndSetState(oldState, newState));
return this;
}
/**
* Set the exception for this operation. Any threads blocking on this instance will be unblocked.
*
* @param exception the exception to set
* @return {@code false} if the operation was already completed, {@code true} otherwise
*/
protected boolean setException(IOException exception) {
State<T> oldState;
oldState = getState();
if (oldState.getStatus() != Status.WAITING) {
return false;
} else {
State<T> newState = new FailedState<T>(exception);
while (! compareAndSetState(oldState, newState)) {
oldState = getState();
if (oldState.getStatus() != Status.WAITING) {
return false;
}
}
}
oldState.notifyFailed(this, exception);
return true;
}
/**
* Set the result for this operation. Any threads blocking on this instance will be unblocked.
*
* @param result the result to set
* @return {@code false} if the operation was already completed, {@code true} otherwise
*/
protected boolean setResult(T result) {
State<T> oldState;
oldState = getState();
if (oldState.getStatus() != Status.WAITING) {
return false;
} else {
State<T> newState = new CompleteState<>(result);
while (! compareAndSetState(oldState, newState)) {
oldState = getState();
if (oldState.getStatus() != Status.WAITING) {
return false;
}
}
}
oldState.notifyDone(this, result);
return true;
}
/**
* Acknowledge the cancellation of this operation.
*
* @return {@code false} if the operation was already completed, {@code true} otherwise
*/
protected boolean setCancelled() {
State<T> oldState;
oldState = getState();
if (oldState.getStatus() != Status.WAITING) {
return false;
} else {
@SuppressWarnings("unchecked")
State<T> newState = (State<T>) ST_CANCELLED;
while (! compareAndSetState(oldState, newState)) {
oldState = getState();
if (oldState.getStatus() != Status.WAITING) {
return false;
}
}
}
oldState.notifyCancelled(this);
return true;
}
/**
* Cancel an operation. The actual cancel may be synchronous or asynchronous. Implementers will use this method
* to initiate the cancel; use the {@link #setCancelled()} method to indicate that the cancel was successful. The
* default implementation calls any registered cancel handlers.
*
* @return this {@code IoFuture} instance
*/
public IoFuture<T> cancel() {
State<T> state;
do {
state = getState();
if (state.getStatus() != Status.WAITING || state.cancelRequested()) return this;
} while (! compareAndSetState(state, new CancelRequestedState<T>(state)));
state.cancel();
return this;
}
/**
* Add a cancellation handler. The argument will be cancelled whenever this {@code IoFuture} is cancelled. If
* the {@code IoFuture} is already cancelled when this method is called, the handler will be called directly.
*
* @param cancellable the cancel handler
*/
protected void addCancelHandler(final Cancellable cancellable) {
State<T> oldState, newState;
do {
oldState = getState();
if (oldState.getStatus() != Status.WAITING || oldState.cancelRequested()) {
try {
cancellable.cancel();
} catch (Throwable ignored) {
}
return;
}
newState = oldState.withCancelHandler(cancellable);
if (oldState == newState) return;
} while (! compareAndSetState(oldState, newState));
}
/**
* Run a notifier. Implementors will run the notifier, preferably in another thread. The default implementation
* runs the notifier using the {@code Executor} retrieved via {@link #getNotifierExecutor()}.
*
* @param runnable the runnable task
*/
protected void runNotifier(final Runnable runnable) {
getNotifierExecutor().execute(runnable);
}
/**
* Get the executor used to run asynchronous notifiers. By default, this implementation simply returns the direct
* executor.
*
* @return the executor to use
*/
protected Executor getNotifierExecutor() {
return IoUtils.directExecutor();
}
static class NotifierRunnable<T, A> implements Runnable {
private final Notifier<? super T, A> notifier;
private final IoFuture<T> future;
private final A attachment;
NotifierRunnable(final Notifier<? super T, A> notifier, final IoFuture<T> future, final A attachment) {
this.notifier = notifier;
this.future = future;
this.attachment = attachment;
}
public void run() {
try {
notifier.notify(future, attachment);
} catch (Throwable t) {
futureMsg.notifierFailed(t, notifier, attachment);
}
}
}
}