-
-
Notifications
You must be signed in to change notification settings - Fork 732
Expand file tree
/
Copy pathTask.java
More file actions
995 lines (911 loc) · 39.5 KB
/
Task.java
File metadata and controls
995 lines (911 loc) · 39.5 KB
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
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.parse.boltsinternal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.CancellationException;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Represents the result of an asynchronous operation.
*
* @param <TResult> The type of the result of the task.
*/
public class Task<TResult> {
/** An {@link java.util.concurrent.Executor} that executes tasks in parallel. */
public static final ExecutorService BACKGROUND_EXECUTOR = BoltsExecutors.background();
/** An {@link java.util.concurrent.Executor} that executes tasks on the UI thread. */
public static final Executor UI_THREAD_EXECUTOR = AndroidExecutors.uiThread();
/**
* An {@link java.util.concurrent.Executor} that executes tasks in the current thread unless the
* stack runs too deep, at which point it will delegate to {@link Task#BACKGROUND_EXECUTOR} in
* order to trim the stack.
*/
private static final Executor IMMEDIATE_EXECUTOR = BoltsExecutors.immediate();
private static final Task<?> TASK_NULL = new Task<>(null);
private static final Task<Boolean> TASK_TRUE = new Task<>((Boolean) true);
private static final Task<Boolean> TASK_FALSE = new Task<>((Boolean) false);
private static final Task<?> TASK_CANCELLED = new Task<>(true);
// null unless explicitly set
private static volatile UnobservedExceptionHandler unobservedExceptionHandler;
private final Object lock = new Object();
private boolean complete;
private boolean cancelled;
private TResult result;
private Exception error;
private boolean errorHasBeenObserved;
private UnobservedErrorNotifier unobservedErrorNotifier;
private List<Continuation<TResult, Void>> continuations = new ArrayList<>();
/* package */ Task() {}
private Task(TResult result) {
trySetResult(result);
}
private Task(boolean cancelled) {
if (cancelled) {
trySetCancelled();
} else {
trySetResult(null);
}
}
/** Returns the handler invoked when a task has an unobserved exception or {@code null}. */
public static UnobservedExceptionHandler getUnobservedExceptionHandler() {
return unobservedExceptionHandler;
}
/**
* Set the handler invoked when a task has an unobserved exception.
*
* @param eh the object to use as an unobserved exception handler. If <tt>null</tt> then
* unobserved exceptions will be ignored.
*/
public static void setUnobservedExceptionHandler(UnobservedExceptionHandler eh) {
unobservedExceptionHandler = eh;
}
/** Creates a completed task with the given value. */
@SuppressWarnings("unchecked")
public static <TResult> Task<TResult> forResult(TResult value) {
if (value == null) {
return (Task<TResult>) TASK_NULL;
}
if (value instanceof Boolean) {
return (Task<TResult>) ((Boolean) value ? TASK_TRUE : TASK_FALSE);
}
com.parse.boltsinternal.TaskCompletionSource<TResult> tcs =
new com.parse.boltsinternal.TaskCompletionSource<>();
tcs.setResult(value);
return tcs.getTask();
}
/** Creates a faulted task with the given error. */
public static <TResult> Task<TResult> forError(Exception error) {
com.parse.boltsinternal.TaskCompletionSource<TResult> tcs =
new com.parse.boltsinternal.TaskCompletionSource<>();
tcs.setError(error);
return tcs.getTask();
}
/** Creates a cancelled task. */
@SuppressWarnings("unchecked")
public static <TResult> Task<TResult> cancelled() {
return (Task<TResult>) TASK_CANCELLED;
}
/**
* Creates a task that completes after a time delay.
*
* @param delay The number of milliseconds to wait before completing the returned task. Zero and
* negative values are treated as requests for immediate execution.
*/
public static Task<Void> delay(long delay) {
return delay(delay, BoltsExecutors.scheduled(), null);
}
/**
* Creates a task that completes after a time delay.
*
* @param delay The number of milliseconds to wait before completing the returned task. Zero and
* negative values are treated as requests for immediate execution.
* @param cancellationToken The optional cancellation token that will be checked prior to
* completing the returned task.
*/
public static Task<Void> delay(long delay, CancellationToken cancellationToken) {
return delay(delay, BoltsExecutors.scheduled(), cancellationToken);
}
/* package */
static Task<Void> delay(
long delay,
ScheduledExecutorService executor,
final CancellationToken cancellationToken) {
if (cancellationToken != null && cancellationToken.isCancellationRequested()) {
return Task.cancelled();
}
if (delay <= 0) {
return Task.forResult(null);
}
final com.parse.boltsinternal.TaskCompletionSource<Void> tcs =
new com.parse.boltsinternal.TaskCompletionSource<>();
final ScheduledFuture<?> scheduled =
executor.schedule(
() -> {
tcs.trySetResult(null);
},
delay,
TimeUnit.MILLISECONDS);
if (cancellationToken != null) {
cancellationToken.register(
() -> {
scheduled.cancel(true);
tcs.trySetCancelled();
});
}
return tcs.getTask();
}
/**
* Invokes the callable on a background thread, returning a Task to represent the operation.
*
* <p>If you want to cancel the resulting Task throw a {@link
* java.util.concurrent.CancellationException} from the callable.
*/
public static <TResult> Task<TResult> callInBackground(Callable<TResult> callable) {
return call(callable, BACKGROUND_EXECUTOR, null);
}
/** Invokes the callable on a background thread, returning a Task to represent the operation. */
public static <TResult> Task<TResult> callInBackground(
Callable<TResult> callable, CancellationToken ct) {
return call(callable, BACKGROUND_EXECUTOR, ct);
}
/**
* Invokes the callable using the given executor, returning a Task to represent the operation.
*
* <p>If you want to cancel the resulting Task throw a {@link
* java.util.concurrent.CancellationException} from the callable.
*/
public static <TResult> Task<TResult> call(
final Callable<TResult> callable, Executor executor) {
return call(callable, executor, null);
}
/**
* Invokes the callable using the given executor, returning a Task to represent the operation.
*/
public static <TResult> Task<TResult> call(
final Callable<TResult> callable, Executor executor, final CancellationToken ct) {
final com.parse.boltsinternal.TaskCompletionSource<TResult> tcs =
new com.parse.boltsinternal.TaskCompletionSource<>();
try {
executor.execute(
() -> {
if (ct != null && ct.isCancellationRequested()) {
tcs.setCancelled();
return;
}
try {
tcs.setResult(callable.call());
} catch (CancellationException e) {
tcs.setCancelled();
} catch (Exception e) {
tcs.setError(e);
}
});
} catch (Exception e) {
tcs.setError(new ExecutorException(e));
}
return tcs.getTask();
}
/**
* Invokes the callable on the current thread, producing a Task.
*
* <p>If you want to cancel the resulting Task throw a {@link
* java.util.concurrent.CancellationException} from the callable.
*/
public static <TResult> Task<TResult> call(final Callable<TResult> callable) {
return call(callable, IMMEDIATE_EXECUTOR, null);
}
/** Invokes the callable on the current thread, producing a Task. */
public static <TResult> Task<TResult> call(
final Callable<TResult> callable, CancellationToken ct) {
return call(callable, IMMEDIATE_EXECUTOR, ct);
}
/**
* Creates a task that will complete when any of the supplied tasks have completed.
*
* <p>The returned task will complete when any of the supplied tasks has completed. The returned
* task will always end in the completed state with its result set to the first task to
* complete. This is true even if the first task to complete ended in the canceled or faulted
* state.
*
* @param tasks The tasks to wait on for completion.
* @return A task that represents the completion of one of the supplied tasks. The return task's
* result is the task that completed.
*/
public static <TResult> Task<Task<TResult>> whenAnyResult(
Collection<? extends Task<TResult>> tasks) {
if (tasks.size() == 0) {
return Task.forResult(null);
}
final com.parse.boltsinternal.TaskCompletionSource<Task<TResult>> firstCompleted =
new com.parse.boltsinternal.TaskCompletionSource<>();
final AtomicBoolean isAnyTaskComplete = new AtomicBoolean(false);
for (Task<TResult> task : tasks) {
task.continueWith(
(Continuation<TResult, Void>)
task1 -> {
if (isAnyTaskComplete.compareAndSet(false, true)) {
firstCompleted.setResult(task1);
} else {
Throwable ensureObserved = task1.getError();
}
return null;
});
}
return firstCompleted.getTask();
}
/**
* Creates a task that will complete when any of the supplied tasks have completed.
*
* <p>The returned task will complete when any of the supplied tasks has completed. The returned
* task will always end in the completed state with its result set to the first task to
* complete. This is true even if the first task to complete ended in the canceled or faulted
* state.
*
* @param tasks The tasks to wait on for completion.
* @return A task that represents the completion of one of the supplied tasks. The return task's
* Result is the task that completed.
*/
@SuppressWarnings("unchecked")
public static Task<Task<?>> whenAny(Collection<? extends Task<?>> tasks) {
if (tasks.size() == 0) {
return Task.forResult(null);
}
final com.parse.boltsinternal.TaskCompletionSource<Task<?>> firstCompleted =
new com.parse.boltsinternal.TaskCompletionSource<>();
final AtomicBoolean isAnyTaskComplete = new AtomicBoolean(false);
for (Task<?> task : tasks) {
((Task<Object>) task)
.continueWith(
(Continuation<Object, Void>)
task1 -> {
if (isAnyTaskComplete.compareAndSet(false, true)) {
firstCompleted.setResult(task1);
} else {
Throwable ensureObserved = task1.getError();
}
return null;
});
}
return firstCompleted.getTask();
}
/**
* Creates a task that completes when all of the provided tasks are complete.
*
* <p>If any of the supplied tasks completes in a faulted state, the returned task will also
* complete in a faulted state, where its exception will resolve to that {@link
* java.lang.Exception} if a single task fails or an {@link AggregateException} of all the
* {@link java.lang.Exception}s if multiple tasks fail.
*
* <p>If none of the supplied tasks faulted but at least one of them was cancelled, the returned
* task will end as cancelled.
*
* <p>If none of the tasks faulted and none of the tasks were cancelled, the resulting task will
* end completed. The result of the returned task will be set to a list containing all of the
* results of the supplied tasks in the same order as they were provided (e.g. if the input
* tasks collection contained t1, t2, t3, the output task's result will return an {@code
* List<TResult>} where {@code list.get(0) == t1.getResult(), list.get(1) ==
* t2.getResult(), and list.get(2) == t3.getResult()}).
*
* <p>If the supplied collection contains no tasks, the returned task will immediately
* transition to a completed state before it's returned to the caller. The returned {@code
* List<TResult>} will contain 0 elements.
*
* @param tasks The tasks that the return value will wait for before completing.
* @return A Task that will resolve to {@code List<TResult>} when all the tasks are
* resolved.
*/
public static <TResult> Task<List<TResult>> whenAllResult(
final Collection<? extends Task<TResult>> tasks) {
return whenAll(tasks)
.onSuccess(
task -> {
if (tasks.size() == 0) {
return Collections.emptyList();
}
List<TResult> results = new ArrayList<>();
for (Task<TResult> individualTask : tasks) {
results.add(individualTask.getResult());
}
return results;
});
}
/**
* Creates a task that completes when all of the provided tasks are complete.
*
* <p>If any of the supplied tasks completes in a faulted state, the returned task will also
* complete in a faulted state, where its exception will resolve to that {@link
* java.lang.Exception} if a single task fails or an {@link AggregateException} of all the
* {@link java.lang.Exception}s if multiple tasks fail.
*
* <p>If none of the supplied tasks faulted but at least one of them was cancelled, the returned
* task will end as cancelled.
*
* <p>If none of the tasks faulted and none of the tasks were canceled, the resulting task will
* end in the completed state.
*
* <p>If the supplied collection contains no tasks, the returned task will immediately
* transition to a completed state before it's returned to the caller.
*
* @param tasks The tasks that the return value will wait for before completing.
* @return A Task that will resolve to {@code Void} when all the tasks are resolved.
*/
public static Task<Void> whenAll(Collection<? extends Task<?>> tasks) {
if (tasks.size() == 0) {
return Task.forResult(null);
}
final com.parse.boltsinternal.TaskCompletionSource<Void> allFinished =
new com.parse.boltsinternal.TaskCompletionSource<>();
final ArrayList<Exception> causes = new ArrayList<>();
final Object errorLock = new Object();
final AtomicInteger count = new AtomicInteger(tasks.size());
final AtomicBoolean isCancelled = new AtomicBoolean(false);
for (Task<?> task : tasks) {
@SuppressWarnings("unchecked")
Task<Object> t = (Task<Object>) task;
t.continueWith(
(Continuation<Object, Void>)
task1 -> {
if (task1.isFaulted()) {
synchronized (errorLock) {
causes.add(task1.getError());
}
}
if (task1.isCancelled()) {
isCancelled.set(true);
}
if (count.decrementAndGet() == 0) {
if (causes.size() != 0) {
if (causes.size() == 1) {
allFinished.setError(causes.get(0));
} else {
Exception error =
new AggregateException(
String.format(
"There were %d exceptions.",
causes.size()),
causes);
allFinished.setError(error);
}
} else if (isCancelled.get()) {
allFinished.setCancelled();
} else {
allFinished.setResult(null);
}
}
return null;
});
}
return allFinished.getTask();
}
/**
* Handles the non-async (i.e. the continuation doesn't return a Task) continuation case,
* passing the results of the given Task through to the given continuation and using the results
* of that call to set the result of the TaskContinuationSource.
*
* @param tcs The TaskContinuationSource that will be orchestrated by this call.
* @param continuation The non-async continuation.
* @param task The task being completed.
* @param executor The executor to use when running the continuation (allowing the continuation
* to be scheduled on a different thread).
*/
private static <TContinuationResult, TResult> void completeImmediately(
final com.parse.boltsinternal.TaskCompletionSource<TContinuationResult> tcs,
final Continuation<TResult, TContinuationResult> continuation,
final Task<TResult> task,
Executor executor,
final CancellationToken ct) {
try {
executor.execute(
() -> {
if (ct != null && ct.isCancellationRequested()) {
tcs.setCancelled();
return;
}
try {
TContinuationResult result = continuation.then(task);
tcs.setResult(result);
} catch (CancellationException e) {
tcs.setCancelled();
} catch (Exception e) {
tcs.setError(e);
}
});
} catch (Exception e) {
tcs.setError(new ExecutorException(e));
}
}
/**
* Handles the async (i.e. the continuation does return a Task) continuation case, passing the
* results of the given Task through to the given continuation to get a new Task. The
* TaskCompletionSource's results are only set when the new Task has completed, unwrapping the
* results of the task returned by the continuation.
*
* @param tcs The TaskContinuationSource that will be orchestrated by this call.
* @param continuation The async continuation.
* @param task The task being completed.
* @param executor The executor to use when running the continuation (allowing the continuation
* to be scheduled on a different thread).
*/
private static <TContinuationResult, TResult> void completeAfterTask(
final com.parse.boltsinternal.TaskCompletionSource<TContinuationResult> tcs,
final Continuation<TResult, Task<TContinuationResult>> continuation,
final Task<TResult> task,
final Executor executor,
final CancellationToken ct) {
try {
executor.execute(
() -> {
if (ct != null && ct.isCancellationRequested()) {
tcs.setCancelled();
return;
}
try {
Task<TContinuationResult> result = continuation.then(task);
if (result == null) {
tcs.setResult(null);
} else {
result.continueWith(
(Continuation<TContinuationResult, Void>)
task1 -> {
if (ct != null
&& ct.isCancellationRequested()) {
tcs.setCancelled();
return null;
}
if (task1.isCancelled()) {
tcs.setCancelled();
} else if (task1.isFaulted()) {
tcs.setError(task1.getError());
} else {
tcs.setResult(task1.getResult());
}
return null;
});
}
} catch (CancellationException e) {
tcs.setCancelled();
} catch (Exception e) {
tcs.setError(e);
}
});
} catch (Exception e) {
tcs.setError(new ExecutorException(e));
}
}
/**
* @return {@code true} if the task completed (has a result, an error, or was cancelled. {@code
* false} otherwise.
*/
public boolean isCompleted() {
synchronized (lock) {
return complete;
}
}
/**
* @return {@code true} if the task was cancelled, {@code false} otherwise.
*/
public boolean isCancelled() {
synchronized (lock) {
return cancelled;
}
}
/**
* @return {@code true} if the task has an error, {@code false} otherwise.
*/
public boolean isFaulted() {
synchronized (lock) {
return getError() != null;
}
}
/**
* @return The result of the task, if set. {@code null} otherwise.
*/
public TResult getResult() {
synchronized (lock) {
return result;
}
}
/**
* @return The error for the task, if set. {@code null} otherwise.
*/
public Exception getError() {
synchronized (lock) {
if (error != null) {
errorHasBeenObserved = true;
if (unobservedErrorNotifier != null) {
unobservedErrorNotifier.setObserved();
unobservedErrorNotifier = null;
}
}
return error;
}
}
/** Blocks until the task is complete. */
public void waitForCompletion() throws InterruptedException {
synchronized (lock) {
if (!isCompleted()) {
lock.wait();
}
}
}
/**
* Blocks until the task is complete or times out.
*
* @return {@code true} if the task completed (has a result, an error, or was cancelled). {@code
* false} otherwise.
*/
public boolean waitForCompletion(long duration, TimeUnit timeUnit) throws InterruptedException {
synchronized (lock) {
if (!isCompleted()) {
lock.wait(timeUnit.toMillis(duration));
}
return isCompleted();
}
}
/**
* Makes a fluent cast of a Task's result possible, avoiding an extra continuation just to cast
* the type of the result.
*/
public <TOut> Task<TOut> cast() {
@SuppressWarnings("unchecked")
Task<TOut> task = (Task<TOut>) this;
return task;
}
/** Turns a Task<T> into a Task<Void>, dropping any result. */
public Task<Void> makeVoid() {
return this.continueWithTask(
task -> {
if (task.isCancelled()) {
return Task.cancelled();
}
if (task.isFaulted()) {
return Task.forError(task.getError());
}
return Task.forResult(null);
});
}
/**
* Continues a task with the equivalent of a Task-based while loop, where the body of the loop
* is a task continuation.
*/
public Task<Void> continueWhile(
Callable<Boolean> predicate, Continuation<Void, Task<Void>> continuation) {
return continueWhile(predicate, continuation, IMMEDIATE_EXECUTOR, null);
}
/**
* Continues a task with the equivalent of a Task-based while loop, where the body of the loop
* is a task continuation.
*/
public Task<Void> continueWhile(
Callable<Boolean> predicate,
Continuation<Void, Task<Void>> continuation,
CancellationToken ct) {
return continueWhile(predicate, continuation, IMMEDIATE_EXECUTOR, ct);
}
/**
* Continues a task with the equivalent of a Task-based while loop, where the body of the loop
* is a task continuation.
*/
public Task<Void> continueWhile(
final Callable<Boolean> predicate,
final Continuation<Void, Task<Void>> continuation,
final Executor executor) {
return continueWhile(predicate, continuation, executor, null);
}
/**
* Continues a task with the equivalent of a Task-based while loop, where the body of the loop
* is a task continuation.
*/
public Task<Void> continueWhile(
final Callable<Boolean> predicate,
final Continuation<Void, Task<Void>> continuation,
final Executor executor,
final CancellationToken ct) {
final Capture<Continuation<Void, Task<Void>>> predicateContinuation = new Capture<>();
predicateContinuation.set(
task -> {
if (ct != null && ct.isCancellationRequested()) {
return Task.cancelled();
}
if (predicate.call()) {
return Task.<Void>forResult(null)
.onSuccessTask(continuation, executor)
.onSuccessTask(predicateContinuation.get(), executor);
}
return Task.forResult(null);
});
return makeVoid().continueWithTask(predicateContinuation.get(), executor);
}
/**
* Adds a continuation that will be scheduled using the executor, returning a new task that
* completes after the continuation has finished running. This allows the continuation to be
* scheduled on different thread.
*/
public <TContinuationResult> Task<TContinuationResult> continueWith(
final Continuation<TResult, TContinuationResult> continuation,
final Executor executor) {
return continueWith(continuation, executor, null);
}
/**
* Adds a continuation that will be scheduled using the executor, returning a new task that
* completes after the continuation has finished running. This allows the continuation to be
* scheduled on different thread.
*/
public <TContinuationResult> Task<TContinuationResult> continueWith(
final Continuation<TResult, TContinuationResult> continuation,
final Executor executor,
final CancellationToken ct) {
boolean completed;
final com.parse.boltsinternal.TaskCompletionSource<TContinuationResult> tcs =
new com.parse.boltsinternal.TaskCompletionSource<>();
synchronized (lock) {
completed = this.isCompleted();
if (!completed) {
this.continuations.add(
task -> {
completeImmediately(tcs, continuation, task, executor, ct);
return null;
});
}
}
if (completed) {
completeImmediately(tcs, continuation, this, executor, ct);
}
return tcs.getTask();
}
/**
* Adds a synchronous continuation to this task, returning a new task that completes after the
* continuation has finished running.
*/
public <TContinuationResult> Task<TContinuationResult> continueWith(
Continuation<TResult, TContinuationResult> continuation) {
return continueWith(continuation, IMMEDIATE_EXECUTOR, null);
}
/**
* Adds a synchronous continuation to this task, returning a new task that completes after the
* continuation has finished running.
*/
public <TContinuationResult> Task<TContinuationResult> continueWith(
Continuation<TResult, TContinuationResult> continuation, CancellationToken ct) {
return continueWith(continuation, IMMEDIATE_EXECUTOR, ct);
}
/**
* Adds an Task-based continuation to this task that will be scheduled using the executor,
* returning a new task that completes after the task returned by the continuation has
* completed.
*/
public <TContinuationResult> Task<TContinuationResult> continueWithTask(
final Continuation<TResult, Task<TContinuationResult>> continuation,
final Executor executor) {
return continueWithTask(continuation, executor, null);
}
/**
* Adds an Task-based continuation to this task that will be scheduled using the executor,
* returning a new task that completes after the task returned by the continuation has
* completed.
*/
public <TContinuationResult> Task<TContinuationResult> continueWithTask(
final Continuation<TResult, Task<TContinuationResult>> continuation,
final Executor executor,
final CancellationToken ct) {
boolean completed;
final com.parse.boltsinternal.TaskCompletionSource<TContinuationResult> tcs =
new com.parse.boltsinternal.TaskCompletionSource<>();
synchronized (lock) {
completed = this.isCompleted();
if (!completed) {
this.continuations.add(
task -> {
completeAfterTask(tcs, continuation, task, executor, ct);
return null;
});
}
}
if (completed) {
completeAfterTask(tcs, continuation, this, executor, ct);
}
return tcs.getTask();
}
/**
* Adds an asynchronous continuation to this task, returning a new task that completes after the
* task returned by the continuation has completed.
*/
public <TContinuationResult> Task<TContinuationResult> continueWithTask(
Continuation<TResult, Task<TContinuationResult>> continuation) {
return continueWithTask(continuation, IMMEDIATE_EXECUTOR, null);
}
/**
* Adds an asynchronous continuation to this task, returning a new task that completes after the
* task returned by the continuation has completed.
*/
public <TContinuationResult> Task<TContinuationResult> continueWithTask(
Continuation<TResult, Task<TContinuationResult>> continuation, CancellationToken ct) {
return continueWithTask(continuation, IMMEDIATE_EXECUTOR, ct);
}
/**
* Runs a continuation when a task completes successfully, forwarding along {@link
* java.lang.Exception} or cancellation.
*/
public <TContinuationResult> Task<TContinuationResult> onSuccess(
final Continuation<TResult, TContinuationResult> continuation, Executor executor) {
return onSuccess(continuation, executor, null);
}
/**
* Runs a continuation when a task completes successfully, forwarding along {@link
* java.lang.Exception} or cancellation.
*/
public <TContinuationResult> Task<TContinuationResult> onSuccess(
final Continuation<TResult, TContinuationResult> continuation,
Executor executor,
final CancellationToken ct) {
return continueWithTask(
task -> {
if (ct != null && ct.isCancellationRequested()) {
return Task.cancelled();
}
if (task.isFaulted()) {
return Task.forError(task.getError());
} else if (task.isCancelled()) {
return Task.cancelled();
} else {
return task.continueWith(continuation);
}
},
executor);
}
/**
* Runs a continuation when a task completes successfully, forwarding along {@link
* java.lang.Exception}s or cancellation.
*/
public <TContinuationResult> Task<TContinuationResult> onSuccess(
final Continuation<TResult, TContinuationResult> continuation) {
return onSuccess(continuation, IMMEDIATE_EXECUTOR, null);
}
/**
* Runs a continuation when a task completes successfully, forwarding along {@link
* java.lang.Exception}s or cancellation.
*/
public <TContinuationResult> Task<TContinuationResult> onSuccess(
final Continuation<TResult, TContinuationResult> continuation, CancellationToken ct) {
return onSuccess(continuation, IMMEDIATE_EXECUTOR, ct);
}
/**
* Runs a continuation when a task completes successfully, forwarding along {@link
* java.lang.Exception}s or cancellation.
*/
public <TContinuationResult> Task<TContinuationResult> onSuccessTask(
final Continuation<TResult, Task<TContinuationResult>> continuation,
Executor executor) {
return onSuccessTask(continuation, executor, null);
}
/**
* Runs a continuation when a task completes successfully, forwarding along {@link
* java.lang.Exception}s or cancellation.
*/
public <TContinuationResult> Task<TContinuationResult> onSuccessTask(
final Continuation<TResult, Task<TContinuationResult>> continuation,
Executor executor,
final CancellationToken ct) {
return continueWithTask(
task -> {
if (ct != null && ct.isCancellationRequested()) {
return Task.cancelled();
}
if (task.isFaulted()) {
return Task.forError(task.getError());
} else if (task.isCancelled()) {
return Task.cancelled();
} else {
return task.continueWithTask(continuation);
}
},
executor);
}
/**
* Runs a continuation when a task completes successfully, forwarding along {@link
* java.lang.Exception}s or cancellation.
*/
public <TContinuationResult> Task<TContinuationResult> onSuccessTask(
final Continuation<TResult, Task<TContinuationResult>> continuation) {
return onSuccessTask(continuation, IMMEDIATE_EXECUTOR);
}
/**
* Runs a continuation when a task completes successfully, forwarding along {@link
* java.lang.Exception}s or cancellation.
*/
public <TContinuationResult> Task<TContinuationResult> onSuccessTask(
final Continuation<TResult, Task<TContinuationResult>> continuation,
CancellationToken ct) {
return onSuccessTask(continuation, IMMEDIATE_EXECUTOR, ct);
}
private void runContinuations() {
synchronized (lock) {
for (Continuation<TResult, ?> continuation : continuations) {
try {
continuation.then(this);
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
continuations = null;
}
}
/** Sets the cancelled flag on the Task if the Task hasn't already been completed. */
/* package */ boolean trySetCancelled() {
synchronized (lock) {
if (complete) {
return false;
}
complete = true;
cancelled = true;
lock.notifyAll();
runContinuations();
return true;
}
}
/** Sets the result on the Task if the Task hasn't already been completed. */
/* package */ boolean trySetResult(TResult result) {
synchronized (lock) {
if (complete) {
return false;
}
complete = true;
Task.this.result = result;
lock.notifyAll();
runContinuations();
return true;
}
}
/** Sets the error on the Task if the Task hasn't already been completed. */
/* package */ boolean trySetError(Exception error) {
synchronized (lock) {
if (complete) {
return false;
}
complete = true;
Task.this.error = error;
errorHasBeenObserved = false;
lock.notifyAll();
runContinuations();
if (!errorHasBeenObserved && getUnobservedExceptionHandler() != null)
unobservedErrorNotifier = new UnobservedErrorNotifier(this);
return true;
}
}
/**
* Interface for handlers invoked when a failed {@code Task} is about to be finalized, but the
* exception has not been consumed.
*
* <p>The handler will execute in the GC thread, so if the handler needs to do anything time
* consuming or complex it is a good idea to fire off a {@code Task} to handle the exception.
*
* @see #getUnobservedExceptionHandler
* @see #setUnobservedExceptionHandler
*/
public interface UnobservedExceptionHandler {
/**
* Method invoked when the given task has an unobserved exception.
*
* <p>Any exception thrown by this method will be ignored.
*
* @param t the task
* @param e the exception
*/
void unobservedException(Task<?> t, UnobservedTaskException e);
}
}