-
Notifications
You must be signed in to change notification settings - Fork 23
/
ManagedExecutorTest.java
2483 lines (2031 loc) · 115 KB
/
ManagedExecutorTest.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2018,2019 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* 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.eclipse.microprofile.concurrency.tck;
import java.io.CharConversionException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.CancellationException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.Phaser;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
import org.eclipse.microprofile.concurrency.tck.contexts.buffer.Buffer;
import org.eclipse.microprofile.concurrency.tck.contexts.buffer.spi.BufferContextProvider;
import org.eclipse.microprofile.concurrency.tck.contexts.label.Label;
import org.eclipse.microprofile.concurrency.tck.contexts.label.spi.LabelContextProvider;
import org.eclipse.microprofile.concurrency.tck.contexts.priority.spi.ThreadPriorityContextProvider;
import org.eclipse.microprofile.concurrent.ManagedExecutor;
import org.eclipse.microprofile.concurrent.ThreadContext;
import org.eclipse.microprofile.concurrent.spi.ThreadContextProvider;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.testng.Arquillian;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.testng.Assert;
import org.testng.ITestResult;
import org.testng.annotations.Test;
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
public class ManagedExecutorTest extends Arquillian {
/**
* Maximum tolerated wait for an asynchronous operation to complete.
* This is important to ensure that tests don't hang waiting for asynchronous operations to complete.
* Normally these sort of operations will complete in tiny fractions of a second, but we are specifying
* an extremely generous value here to allow for the widest possible variety of test execution environments.
*/
private static final long MAX_WAIT_NS = TimeUnit.MINUTES.toNanos(2);
/**
* Pool of unmanaged threads (not context-aware) that can be used by tests.
*/
private ExecutorService unmanagedThreads;
@AfterClass
public void after() {
unmanagedThreads.shutdownNow();
}
@AfterMethod
public void afterMethod(Method m, ITestResult result) {
System.out.println("<<< END " + m.getClass().getSimpleName() + '.' + m.getName() + (result.isSuccess() ? " SUCCESS" : " FAILED"));
Throwable failure = result.getThrowable();
if (failure != null) {
failure.printStackTrace(System.out);
}
}
@BeforeClass
public void before() {
unmanagedThreads = Executors.newFixedThreadPool(5);
}
@BeforeMethod
public void beforeMethod(Method m) {
System.out.println(">>> BEGIN " + m.getClass().getSimpleName() + '.' + m.getName());
}
@Deployment
public static WebArchive createDeployment() {
// build a JAR that provides three fake context types: 'Buffer', 'Label', and 'ThreadPriority'
JavaArchive fakeContextProviders = ShrinkWrap.create(JavaArchive.class, "fakeContextTypes.jar")
.addPackages(true, "org.eclipse.microprofile.concurrency.tck.contexts.buffer")
.addPackages(true, "org.eclipse.microprofile.concurrency.tck.contexts.label")
.addPackage("org.eclipse.microprofile.concurrency.tck.contexts.priority.spi")
.addAsServiceProvider(ThreadContextProvider.class,
BufferContextProvider.class, LabelContextProvider.class, ThreadPriorityContextProvider.class);
return ShrinkWrap.create(WebArchive.class, ManagedExecutorTest.class.getSimpleName() + ".war")
.addClass(ManagedExecutorTest.class)
.addAsLibraries(fakeContextProviders);
}
@Test
public void builderForManagedExecutorIsProvided() {
Assert.assertNotNull(ManagedExecutor.builder(),
"MicroProfile Concurrency implementation does not provide a ManagedExecutor builder.");
}
/**
* Verify that the MicroProfile Concurrency ManagedExecutor implementation clears context
* types that are not configured under propagated, or cleared.
* @throws TimeoutException
* @throws ExecutionException
* @throws InterruptedException
*/
@Test
public void clearUnspecifiedContexts() throws InterruptedException, ExecutionException, TimeoutException {
ManagedExecutor executor = ManagedExecutor.builder()
.propagated(Buffer.CONTEXT_NAME)
.build();
int originalPriority = Thread.currentThread().getPriority();
try {
// Set non-default values
int newPriority = originalPriority == 3 ? 2 : 3;
Thread.currentThread().setPriority(newPriority);
Buffer.set(new StringBuffer("clearUnspecifiedContexts-test-buffer-A"));
Future<Void> future = executor.completedFuture(1).thenRun(() -> {
Assert.assertEquals(Buffer.get().toString(), "clearUnspecifiedContexts-test-buffer-A",
"Context type was not propagated to contextual action.");
Buffer.set(new StringBuffer("clearUnspecifiedContexts-test-buffer-B"));
Assert.assertEquals(Thread.currentThread().getPriority(), Thread.NORM_PRIORITY,
"Context type that remained unspecified was not cleared by default.");
});
Assert.assertNull(future.get(MAX_WAIT_NS, TimeUnit.NANOSECONDS),
"Non-null value returned by stage that runs Runnable.");
Assert.assertEquals(Buffer.get().toString(), "clearUnspecifiedContexts-test-buffer-A",
"Previous context (Buffer) was not restored after context was propagated for contextual action.");
}
finally {
executor.shutdownNow();
// Restore original values
Buffer.set(null);
Thread.currentThread().setPriority(originalPriority);
}
}
/**
* Verify that thread context is captured and propagated per the configuration of the
* ManagedExecutor builder for all dependent stages of the completed future that is created
* by the ManagedExecutor's completedFuture implementation. Thread context is captured
* at each point where a dependent stage is added, rather than solely upon creation of the
* initial stage or construction of the builder.
*/
@Test
public void completedFutureDependentStagesRunWithContext() throws ExecutionException, InterruptedException, TimeoutException {
ManagedExecutor executor = ManagedExecutor.builder()
.propagated(Buffer.CONTEXT_NAME)
.build();
try {
// Set non-default values
Buffer.set(new StringBuffer("completedFuture-test-buffer-A"));
Label.set("completedFuture-test-label");
CompletableFuture<Long> stage1a = executor.completedFuture(1000L);
Assert.assertTrue(stage1a.isDone(),
"Future created by completedFuture is not complete.");
Assert.assertFalse(stage1a.isCompletedExceptionally(),
"Future created by completedFuture reports exceptional completion.");
Assert.assertEquals(stage1a.getNow(1234L), Long.valueOf(1000L),
"Future created by completedFuture has result that differs from what was specified.");
// The following incomplete future blocks subsequent stages from running inline on the current thread
CompletableFuture<Long> stage1b = new CompletableFuture<Long>();
Buffer.set(new StringBuffer("completedFuture-test-buffer-B"));
CompletableFuture<Long> stage2 = stage1a.thenCombine(stage1b, (a, b) -> {
Assert.assertEquals(a, Long.valueOf(1000L),
"First value supplied to BiFunction was lost or altered.");
Assert.assertEquals(b, Long.valueOf(3L),
"Second value supplied to BiFunction was lost or altered.");
Assert.assertEquals(Buffer.get().toString(), "completedFuture-test-buffer-B",
"Context type was not propagated to contextual action.");
Assert.assertEquals(Label.get(), "",
"Context type that is configured to be cleared was not cleared.");
return a * b;
});
Buffer.set(new StringBuffer("completedFuture-test-buffer-C"));
CompletableFuture<Long> stage3 = stage2.thenApply(i -> {
Assert.assertEquals(i, Long.valueOf(3000L),
"Value supplied to third stage was lost or altered.");
Assert.assertEquals(Buffer.get().toString(), "completedFuture-test-buffer-C",
"Context type was not propagated to contextual action.");
// This stage runs inline on the same thread as the test, so alter the
// context here and later verify that the MicroProfile Concurrency implementation
// properly restores it to the thread's previous value, which will be
// completedFuture-test-buffer-E at the point when this runs.
Buffer.set(new StringBuffer("completedFuture-test-buffer-D"));
Assert.assertEquals(Label.get(), "",
"Context type that is configured to be cleared was not cleared.");
return i - 300;
});
Buffer.set(new StringBuffer("completedFuture-test-buffer-E"));
// Complete stage 1b, allowing stage 2 and then 3 to run
stage1b.complete(3L);
Assert.assertEquals(stage3.get(MAX_WAIT_NS, TimeUnit.NANOSECONDS), Long.valueOf(2700L),
"Unexpected result for stage 3.");
Assert.assertEquals(stage2.getNow(3333L), Long.valueOf(3000L),
"Unexpected or missing result for stage 2.");
Assert.assertTrue(stage2.isDone(), "Second stage did not transition to done upon completion.");
Assert.assertTrue(stage3.isDone(), "Third stage did not transition to done upon completion.");
Assert.assertFalse(stage2.isCompletedExceptionally(), "Second stage should not report exceptional completion.");
Assert.assertFalse(stage3.isCompletedExceptionally(), "Third stage should not report exceptional completion.");
// Is context properly restored on current thread?
Assert.assertEquals(Buffer.get().toString(), "completedFuture-test-buffer-E",
"Previous context was not restored after context was cleared for managed executor tasks.");
Assert.assertEquals(Label.get(), "completedFuture-test-label",
"Previous context was not restored after context was propagated for managed executor tasks.");
}
finally {
executor.shutdownNow();
// Restore original values
Buffer.set(null);
Label.set(null);
}
}
/**
* Verify that thread context is captured and propagated per the configuration of the
* ManagedExecutor builder for all dependent stages of the completed future that is created
* by the ManagedExecutor's completedStage implementation. Thread context is captured
* at each point where a dependent stage is added, rather than solely upon creation of the
* initial stage or construction of the builder.
*/
@Test
public void completedStageDependentStagesRunWithContext() throws InterruptedException {
ManagedExecutor executor = ManagedExecutor.builder()
.propagated(Label.CONTEXT_NAME)
.build();
try {
// Set non-default values
Buffer.set(new StringBuffer("completedStage-test-buffer"));
Label.set("completedStage-test-label-A");
CompletionStage<String> stage1 = executor.completedStage("5A");
// The following incomplete future prevents subsequent stages from completing
CompletableFuture<Integer> stage2 = new CompletableFuture<Integer>();
Label.set("completedStage-test-label-B");
CompletionStage<Integer> stage3 = stage1.thenCompose(s -> {
Assert.assertEquals(s, "5A",
"Value supplied to compose function was lost or altered.");
Assert.assertEquals(Buffer.get().toString(), "",
"Context type that is configured to be cleared was not cleared.");
Assert.assertEquals(Label.get(), "completedStage-test-label-B",
"Context type was not propagated to contextual action.");
return stage2.thenApply(i -> i + Integer.parseInt(s, 16));
});
Label.set("completedStage-test-label-C");
CompletionStage<Integer> stage4 = stage3.applyToEither(new CompletableFuture<Integer>(), i -> {
Assert.assertEquals(i, Integer.valueOf(99),
"Value supplied to function was lost or altered.");
Assert.assertEquals(Buffer.get().toString(), "",
"Context type that is configured to be cleared was not cleared.");
Assert.assertEquals(Label.get(), "completedStage-test-label-C",
"Context type was not propagated to contextual action.");
return i + 1;
});
Label.set("completedStage-test-label-D");
CountDownLatch completed = new CountDownLatch(1);
AtomicInteger resultRef = new AtomicInteger();
stage4.whenComplete((result, failure) -> {
resultRef.set(result);
completed.countDown();
});
// allow stages 3 and 4 to complete
stage2.complete(9);
Assert.assertTrue(completed.await(MAX_WAIT_NS, TimeUnit.NANOSECONDS),
"Completion stage did not finish in a reasonable amount of time.");
Assert.assertEquals(resultRef.get(), 100,
"Unexpected result for stage 4.");
// Is context properly restored on current thread?
Assert.assertEquals(Buffer.get().toString(), "completedStage-test-buffer",
"Previous context was not restored after context was cleared for managed executor tasks.");
Assert.assertEquals(Label.get(), "completedStage-test-label-D",
"Previous context was not restored after context was propagated for managed executor tasks.");
}
finally {
executor.shutdownNow();
// Restore original values
Buffer.set(null);
Label.set(null);
}
}
/**
* Verify the MicroProfile Concurrency implementation of propagate(), and cleared()
* for MangedExecutor.Builder.
*/
@Test
public void contextControlsForManagedExecutorBuilder() throws InterruptedException, ExecutionException, TimeoutException {
ManagedExecutor executor = ManagedExecutor.builder()
.propagated(Buffer.CONTEXT_NAME)
.cleared(Label.CONTEXT_NAME)
.maxAsync(-1)
.maxQueued(-1)
.build();
try {
ManagedExecutor.builder()
.propagated(Buffer.CONTEXT_NAME)
.cleared(Label.CONTEXT_NAME, Buffer.CONTEXT_NAME)
.maxAsync(-1)
.maxQueued(-1)
.build();
Assert.fail("ManagedExecutor.Builder.build() should throw an IllegalStateException for set overlap between propagated and cleared");
}
catch (IllegalStateException ISE) {
// test passes
}
try {
ManagedExecutor.builder()
.propagated(Buffer.CONTEXT_NAME, "BOGUS_CONTEXT")
.cleared(Label.CONTEXT_NAME)
.maxAsync(-1)
.maxQueued(-1)
.build();
Assert.fail("ManagedExecutor.Builder.build() should throw an IllegalStateException for a nonexistent thread context type");
}
catch (IllegalStateException ISE) {
// test passes
}
try {
// Set non-default values
Buffer.get().append("contextControls-test-buffer-A");
Label.set("contextControls-test-label-A");
Future<Void> future = executor.submit(() -> {
Assert.assertEquals(Buffer.get().toString(), "contextControls-test-buffer-A",
"Context type was not propagated to contextual action.");
Buffer.get().append("-B");
Assert.assertEquals(Label.get(), "",
"Context type that is configured to be cleared was not cleared.");
Label.set("contextControls-test-label-B");
return null;
});
Assert.assertNull(future.get(MAX_WAIT_NS, TimeUnit.NANOSECONDS),
"Unexpected result of task.");
Assert.assertEquals(Buffer.get().toString(), "contextControls-test-buffer-A-B",
"Context type was not propagated to contextual action.");
Assert.assertEquals(Label.get(), "contextControls-test-label-A",
"Context type was not left unchanged by contextual action.");
}
finally {
executor.shutdownNow();
// Restore original values
Buffer.set(null);
Label.set(null);
}
}
/**
* When an already-contextualized Callable is specified as the action/task,
* the action/task runs with its already-captured context rather than
* capturing and applying context per the configuration of the managed executor.
*/
@Test
public void contextOfContextualCallableOverridesContextOfManagedExecutor() throws ExecutionException, InterruptedException, TimeoutException {
ThreadContext bufferContext = ThreadContext.builder()
.propagated(Buffer.CONTEXT_NAME)
.cleared(ThreadContext.ALL_REMAINING)
.build();
ManagedExecutor executor = ManagedExecutor.builder()
.propagated(Label.CONTEXT_NAME)
.cleared(ThreadContext.ALL_REMAINING)
.build();
try {
Callable<String> getBuffer = () -> {
Assert.assertEquals(Label.get(), "",
"Context type not cleared from thread.");
return Buffer.get().toString();
};
Callable<String> getLabel = () -> {
Assert.assertEquals(Buffer.get().toString(), "",
"Context type not cleared from thread.");
return Label.get();
};
Buffer.set(new StringBuffer("contextualCallableOverride-buffer-1"));
Label.set("contextualCallableOverride-label-1");
Callable<String> precontextualizedTask1 = bufferContext.contextualCallable(getBuffer);
Buffer.set(new StringBuffer("contextualCallableOverride-buffer-2"));
Label.set("contextualCallableOverride-label-2");
Callable<String> precontextualizedTask2 = bufferContext.contextualCallable(getBuffer);
Buffer.set(new StringBuffer("contextualCallableOverride-buffer-3"));
Label.set("contextualCallableOverride-label-3");
Future<String> future = executor.submit(precontextualizedTask1);
Assert.assertEquals(future.get(MAX_WAIT_NS, TimeUnit.NANOSECONDS), "contextualCallableOverride-buffer-1",
"Previously captured context type not found on thread.");
List<Future<String>> futures = executor.invokeAll(
Arrays.asList(precontextualizedTask2, getLabel, precontextualizedTask1, precontextualizedTask2),
MAX_WAIT_NS,
TimeUnit.NANOSECONDS);
future = futures.get(0);
Assert.assertEquals(future.get(), "contextualCallableOverride-buffer-2",
"Previously captured context type not found on thread.");
future = futures.get(1);
Assert.assertEquals(future.get(), "contextualCallableOverride-label-3",
"Context type captured by managed executor not found on thread.");
future = futures.get(2);
Assert.assertEquals(future.get(), "contextualCallableOverride-buffer-1",
"Previously captured context type not found on thread.");
future = futures.get(3);
Assert.assertEquals(future.get(), "contextualCallableOverride-buffer-2",
"Previously captured context type not found on thread.");
String result = executor.invokeAny(
Arrays.asList(precontextualizedTask1, precontextualizedTask1),
MAX_WAIT_NS,
TimeUnit.NANOSECONDS);
Assert.assertEquals(result, "contextualCallableOverride-buffer-1",
"Previously captured context type not found on thread.");
}
finally {
executor.shutdownNow();
// Restore original values
Buffer.set(null);
Label.set(null);
}
}
/**
* When an already-contextualized Consumer or BiFunction is specified as the action/task,
* the action/task runs with its already-captured context rather than
* capturing and applying context per the configuration of the managed executor.
*/
@Test
public void contextOfContextualConsumerAndBiFunctionOverrideContextOfManagedExecutor()
throws ExecutionException, InterruptedException, TimeoutException {
ThreadContext labelContext = ThreadContext.builder()
.propagated(Label.CONTEXT_NAME)
.cleared(ThreadContext.ALL_REMAINING)
.build();
ManagedExecutor executor = ManagedExecutor.builder()
.propagated(Buffer.CONTEXT_NAME)
.cleared(ThreadContext.ALL_REMAINING)
.build();
try {
Buffer.set(new StringBuffer("contextualBiFunctionOverride-buffer-1"));
Label.set("contextualBiFunctionOverride-label-1");
BiFunction<Integer, Throwable, Integer> precontextualizedFunction1 = labelContext.contextualFunction((result, failure) -> {
Assert.assertEquals(Label.get(), "contextualBiFunctionOverride-label-1",
"Previously captured context type not found on thread.");
Assert.assertEquals(Buffer.get().toString(), "",
"Context type not cleared from thread.");
return failure == null ? result : 100;
});
Buffer.set(new StringBuffer("contextualBiFunctionOverride-buffer-2"));
Label.set("contextualBiFunctionOverride-label-2");
BiFunction<Integer, Integer, Integer> precontextualizedFunction2 = labelContext.contextualFunction((i, j) -> {
Assert.assertEquals(Label.get(), "contextualBiFunctionOverride-label-2",
"Previously captured context type not found on thread.");
Assert.assertEquals(Buffer.get().toString(), "",
"Context type not cleared from thread.");
return i - j;
});
Buffer.set(new StringBuffer("contextualConsumerOverride-buffer-3"));
Label.set("contextualConsumerOverride-label-3");
Consumer<Integer> precontextualizedConsumer3 = labelContext.contextualConsumer(i -> {
Assert.assertEquals(Label.get(), "contextualConsumerOverride-label-3",
"Previously captured context type not found on thread.");
Assert.assertEquals(Buffer.get().toString(), "",
"Context type not cleared from thread.");
});
Buffer.set(new StringBuffer("contextualConsuemrOverride-buffer-4"));
Label.set("contextualConsumerOverride-label-4");
Consumer<Integer> precontextualizedConsumer4 = labelContext.contextualConsumer(i -> {
Assert.assertEquals(Label.get(), "contextualConsumerOverride-label-4",
"Previously captured context type not found on thread.");
Assert.assertEquals(Buffer.get().toString(), "",
"Context type not cleared from thread.");
});
BiFunction<Void, Void, String> normalFunction5 = (unused1, unused2) -> {
Assert.assertEquals(Buffer.get().toString(), "contextualConsumerAndBiFunctionOverride-buffer-5",
"Previously captured context type not found on thread.");
Assert.assertEquals(Label.get(), "",
"Context type not cleared from thread.");
return "done";
};
Buffer.set(new StringBuffer("contextualConsumerAndBiFunctionOverride-buffer-5"));
Label.set("contextualConsumerAndBiFunctionOverride-label-5");
CompletableFuture<Integer> stage0 = executor.failedFuture(new ArrayIndexOutOfBoundsException("Expected error."));
CompletableFuture<Integer> stage1 = stage0.handleAsync(precontextualizedFunction1);
CompletableFuture<Integer> stage2 = executor.completedFuture(200).thenCombineAsync(stage1, precontextualizedFunction2);
CompletableFuture<Void> stage3 = stage2.thenAccept(precontextualizedConsumer3);
CompletableFuture<Void> stage4 = stage2.acceptEitherAsync(stage1, precontextualizedConsumer4);
CompletableFuture<String> stage5 = stage4.thenCombine(stage3, normalFunction5);
Assert.assertEquals(stage5.join(), "done",
"Unexpected result for completion stage.");
}
finally {
executor.shutdownNow();
// Restore original values
Buffer.set(null);
Label.set(null);
}
}
/**
* When an already-contextualized Function is specified as the action/task,
* the action/task runs with its already-captured context rather than
* capturing and applying context per the configuration of the managed executor.
*/
@Test
public void contextOfContextualFunctionOverridesContextOfManagedExecutor() throws ExecutionException, InterruptedException, TimeoutException {
ThreadContext labelContext = ThreadContext.builder()
.propagated(Label.CONTEXT_NAME)
.cleared(ThreadContext.ALL_REMAINING)
.build();
ManagedExecutor executor = ManagedExecutor.builder()
.propagated(Buffer.CONTEXT_NAME)
.cleared(ThreadContext.ALL_REMAINING)
.build();
try {
Buffer.set(new StringBuffer("contextualFunctionOverride-buffer-1"));
Label.set("contextualFunctionOverride-label-1");
Function<Integer, Integer> precontextualizedFunction1 = labelContext.contextualFunction(i -> {
Assert.assertEquals(Label.get(), "contextualFunctionOverride-label-1",
"Previously captured context type not found on thread.");
Assert.assertEquals(Buffer.get().toString(), "",
"Context type not cleared from thread.");
return i + 1;
});
Buffer.set(new StringBuffer("contextualFunctionOverride-buffer-2"));
Label.set("contextualFunctionOverride-label-2");
Function<Integer, Integer> precontextualizedFunction2 = labelContext.contextualFunction(i -> {
Assert.assertEquals(Label.get(), "contextualFunctionOverride-label-2",
"Previously captured context type not found on thread.");
Assert.assertEquals(Buffer.get().toString(), "",
"Context type not cleared from thread.");
return i + 20;
});
Function<Throwable, Integer> precontextualizedErrorHandler = labelContext.contextualFunction(failure -> {
Assert.assertEquals(Label.get(), "contextualFunctionOverride-label-2",
"Previously captured context type not found on thread.");
Assert.assertEquals(Buffer.get().toString(), "",
"Context type not cleared from thread.");
return -1;
});
Buffer.set(new StringBuffer("contextualFunctionOverride-buffer-3"));
Label.set("contextualFunctionOverride-label-3");
Function<Integer, Integer> normalFunction = i -> {
Assert.assertEquals(Buffer.get().toString(), "contextualFunctionOverride-buffer-3",
"Previously captured context type not found on thread.");
Assert.assertEquals(Label.get(), "",
"Context type not cleared from thread.");
return i + 300;
};
CompletableFuture<Integer> stage0 = executor.newIncompleteFuture();
CompletableFuture<Integer> stage1 = stage0.thenApplyAsync(precontextualizedFunction1);
Buffer.set(new StringBuffer("contextualFunctionOverride-buffer-4"));
Label.set("contextualFunctionOverride-label-4");
Function<Integer, CompletableFuture<Integer>> precontextualizedFunction4 = labelContext.contextualFunction(i -> {
Assert.assertEquals(Label.get(), "contextualFunctionOverride-label-4",
"Previously captured context type not found on thread.");
Assert.assertEquals(Buffer.get().toString(), "",
"Context type not cleared from thread.");
return stage1;
});
Buffer.set(new StringBuffer("contextualFunctionOverride-buffer-3"));
Label.set("contextualFunctionOverride-label-3");
CompletableFuture<Integer> stage2 = stage0.thenComposeAsync(precontextualizedFunction4);
CompletableFuture<Integer> stage3 = stage2.applyToEither(stage1, precontextualizedFunction2);
CompletableFuture<Integer> stage4 = stage3.thenApply(normalFunction);
CompletableFuture<Integer> stage5 = stage4.thenApply(i -> i / (i - 321)) // intentional ArithmeticException for division by 0
.exceptionally(precontextualizedErrorHandler);
stage0.complete(0);
Assert.assertEquals(stage2.join(), Integer.valueOf(1),
"Unexpected result for completion stage.");
Assert.assertEquals(stage5.join(), Integer.valueOf(-1),
"Unexpected result for completion stage.");
}
finally {
executor.shutdownNow();
// Restore original values
Buffer.set(null);
Label.set(null);
}
}
/**
* When an already-contextualized Runnable is specified as the action/task,
* the action/task runs with its already-captured context rather than
* capturing and applying context per the configuration of the managed executor.
*/
@Test
public void contextOfContextualRunnableOverridesContextOfManagedExecutor() throws ExecutionException, InterruptedException, TimeoutException {
ThreadContext labelContext = ThreadContext.builder()
.propagated(Label.CONTEXT_NAME)
.cleared(ThreadContext.ALL_REMAINING)
.build();
ManagedExecutor executor = ManagedExecutor.builder()
.propagated(Buffer.CONTEXT_NAME)
.cleared(ThreadContext.ALL_REMAINING)
.build();
try {
Buffer.set(new StringBuffer("contextualRunnableOverride-buffer-1"));
Label.set("contextualRunnableOverride-label-1");
Runnable precontextualizedTask1 = labelContext.contextualRunnable(() -> {
Assert.assertEquals(Label.get(), "contextualRunnableOverride-label-1",
"Previously captured context type not found on thread.");
Assert.assertEquals(Buffer.get().toString(), "",
"Context type not cleared from thread.");
});
Buffer.set(new StringBuffer("contextualRunnableOverride-buffer-2"));
Label.set("contextualRunnableOverride-label-2");
Runnable precontextualizedTask2 = labelContext.contextualRunnable(() -> {
Assert.assertEquals(Label.get(), "contextualRunnableOverride-label-2",
"Previously captured context type not found on thread.");
Assert.assertEquals(Buffer.get().toString(), "",
"Context type not cleared from thread.");
});
Buffer.set(new StringBuffer("contextualRunnableOverride-buffer-3"));
Label.set("contextualRunnableOverride-label-3");
Runnable normalTask = () -> {
Assert.assertEquals(Buffer.get().toString(), "contextualRunnableOverride-buffer-3",
"Previously captured context type not found on thread.");
Assert.assertEquals(Label.get(), "",
"Context type not cleared from thread.");
};
Future<Integer> future = executor.submit(precontextualizedTask1, 1);
Assert.assertEquals(future.get(MAX_WAIT_NS, TimeUnit.NANOSECONDS), Integer.valueOf(1),
"Unexpected result of task.");
CompletableFuture<Void> stage0 = executor.runAsync(precontextualizedTask1);
CompletableFuture<Void> stage1 = stage0.thenRunAsync(precontextualizedTask1);
CompletableFuture<Void> stage2 = stage0.thenRun(precontextualizedTask2);
CompletableFuture<Void> stage3 = stage1.runAfterEither(stage2, precontextualizedTask2);
CompletableFuture<Void> stage4 = stage1.runAfterBothAsync(stage2, precontextualizedTask1);
CompletableFuture<Void> stage5 = stage4.runAfterBoth(stage3, normalTask);
stage5.join();
LinkedBlockingQueue<String> results = new LinkedBlockingQueue<String>();
Runnable precontextualizedTask3 = labelContext.contextualRunnable(() -> results.add(Label.get()));
Buffer.set(new StringBuffer("contextualRunnableOverride-buffer-3"));
Label.set("contextualRunnableOverride-label-3");
executor.execute(precontextualizedTask3);
Assert.assertEquals(results.poll(MAX_WAIT_NS, TimeUnit.NANOSECONDS), "contextualRunnableOverride-label-3",
"Previously captured context type not found on thread.");
}
finally {
executor.shutdownNow();
// Restore original values
Buffer.set(null);
Label.set(null);
}
}
/**
* When an already-contextualized Supplier or BiFunction is specified as the action/task,
* the action/task runs with its already-captured context rather than
* capturing and applying context per the configuration of the managed executor.
*/
@Test
public void contextOfContextualSuppplierAndBiConsumerOverrideContextOfManagedExecutor()
throws ExecutionException, InterruptedException, TimeoutException {
ThreadContext bufferContext = ThreadContext.builder()
.propagated(Buffer.CONTEXT_NAME)
.cleared(ThreadContext.ALL_REMAINING)
.build();
ManagedExecutor executor = ManagedExecutor.builder()
.propagated(Label.CONTEXT_NAME)
.cleared(ThreadContext.ALL_REMAINING)
.build();
try {
Supplier<String> getBuffer = () -> {
Assert.assertEquals(Label.get(), "",
"Context type not cleared from thread.");
return Buffer.get().toString();
};
Buffer.set(new StringBuffer("contextualSupplierOverride-buffer-1"));
Label.set("contextualSupplierOverride-label-1");
Supplier<String> precontextualizedSupplier1 = bufferContext.contextualSupplier(getBuffer);
Buffer.set(new StringBuffer("contextualSupplierOverride-buffer-2"));
Label.set("contextualSupplierOverride-label-2");
Supplier<String> precontextualizedSupplier2 = bufferContext.contextualSupplier(getBuffer);
Buffer.set(new StringBuffer("contextualBiConsumerOverride-buffer-3"));
Label.set("contextualBiConsumerOverride-label-3");
BiConsumer<String, String> precontextualizedConsumer3 = bufferContext.contextualConsumer((b1, b2) -> {
Assert.assertEquals(Buffer.get().toString(), "contextualBiConsumerOverride-buffer-3",
"Previously captured context type not found on thread.");
Assert.assertEquals(Label.get(), "",
"Context type not cleared from thread.");
Assert.assertEquals(b1, "contextualSupplierOverride-buffer-1",
"Previously captured context type not found on Supplier's thread.");
Assert.assertEquals(b2, "contextualSupplierOverride-buffer-2",
"Previously captured context type not found on Supplier's thread.");
});
Buffer.set(new StringBuffer("contextualBiConsumerOverride-buffer-4"));
Label.set("contextualBiConsumerOverride-label-4");
BiConsumer<Void, Throwable> precontextualizedConsumer4 = bufferContext.contextualConsumer((unused, failure) -> {
Assert.assertEquals(Buffer.get().toString(), "contextualBiConsumerOverride-buffer-4",
"Previously captured context type not found on thread.");
Assert.assertEquals(Label.get(), "",
"Context type not cleared from thread.");
});
Buffer.set(new StringBuffer("contextualSupplierAndBiConsumerOverride-buffer-5"));
Label.set("contextualSupplierAndBiConsumerOverride-label-5");
CompletableFuture<String> stage1 = executor.supplyAsync(precontextualizedSupplier1);
CompletableFuture<String> stage2 = executor.supplyAsync(precontextualizedSupplier2);
CompletableFuture<Void> stage3 = stage1.thenAcceptBoth(stage2, precontextualizedConsumer3);
CompletableFuture<Void> stage4 = stage3.whenCompleteAsync(precontextualizedConsumer4);
CompletableFuture<Void> stage5 = stage4.whenComplete((unused, failure) -> {
Assert.assertEquals(Label.get(), "contextualSupplierAndBiConsumerOverride-label-5",
"Context type captured by managed executor not found on thread.");
Assert.assertEquals(Buffer.get().toString(), "",
"Context type not cleared from thread.");
});
stage5.join();
}
finally {
executor.shutdownNow();
// Restore original values
Buffer.set(null);
Label.set(null);
}
}
/**
* Verify that thread context is cleared per the configuration of the ManagedExecutor builder
* for all tasks that are executed via the execute method. This test supplies the ManagedExecutor
* to a Java SE CompletableFuture, which invokes the execute method to run tasks asynchronously.
*/
@Test
public void executedTaskRunsWithClearedContext() throws ExecutionException, InterruptedException, TimeoutException {
ManagedExecutor executor = ManagedExecutor.builder()
.propagated()
.cleared(ThreadContext.ALL_REMAINING)
.build();
try {
Buffer.set(new StringBuffer("executed-task-test-buffer-A"));
Label.set("executed-task-test-label-A");
CompletableFuture<Integer> cf1 = new CompletableFuture<Integer>();
CompletableFuture<Void> cf2 = cf1.thenAcceptAsync(i -> {
Assert.assertEquals(Buffer.get().toString(), "",
"Context type that is configured to be cleared was not cleared.");
Assert.assertEquals(Label.get(), "",
"Context type that is configured to be cleared was not cleared.");
Label.set("executed-task-test-label-B");
}, executor);
cf1.complete(1000);
cf2.join();
Assert.assertEquals(Buffer.get().toString(), "executed-task-test-buffer-A",
"Context unexpectedly changed on thread.");
Assert.assertEquals(Label.get(), "executed-task-test-label-A",
"Context unexpectedly changed on thread.");
}
finally {
executor.shutdownNow();
// Restore original values
Buffer.set(null);
Label.set(null);
}
}
/**
* Verify that thread context is propagated per the configuration of the ManagedExecutor builder
* for all tasks that are executed via the execute method.
*/
@Test
public void executedTaskRunsWithContext() throws ExecutionException, InterruptedException, TimeoutException {
ManagedExecutor executor = ManagedExecutor.builder()
.propagated(Buffer.CONTEXT_NAME, Label.CONTEXT_NAME)
.cleared(ThreadContext.ALL_REMAINING)
.build();
try {
Buffer.set(new StringBuffer("executed-task-test-buffer-C"));
Label.set("executed-task-test-label-C");
CompletableFuture<String> result = new CompletableFuture<String>();
executor.execute(() -> {
try {
Assert.assertEquals(Buffer.get().toString(), "executed-task-test-buffer-C",
"Context type that is configured to be propagated was not propagated.");
Assert.assertEquals(Label.get(), "executed-task-test-label-C",
"Context type that is configured to be propagated was not propagated.");
Label.set("executed-task-test-label-D");
result.complete("successful");
}
catch (Throwable x) {
result.completeExceptionally(x);
}
});
// Force exception to be raised, if any
result.get(MAX_WAIT_NS, TimeUnit.NANOSECONDS);
Assert.assertEquals(Buffer.get().toString(), "executed-task-test-buffer-C",
"Context unexpectedly changed on thread.");
Assert.assertEquals(Label.get(), "executed-task-test-label-C",
"Context unexpectedly changed on thread.");
}
finally {
executor.shutdownNow();
// Restore original values
Buffer.set(null);
Label.set(null);
}
}
/**
* Verify that thread context is captured and propagated per the configuration of the
* ManagedExecutor builder for all dependent stages of the completed future that is created
* by the ManagedExecutor's failedFuture implementation. Thread context is captured
* at each point where a dependent stage is added, rather than solely upon creation of the
* initial stage or construction of the builder.
*/
@Test
public void failedFutureDependentStagesRunWithContext() throws ExecutionException, InterruptedException, TimeoutException {
ManagedExecutor executor = ManagedExecutor.builder()
.propagated(Buffer.CONTEXT_NAME)
.build();
try {
// Set non-default values
Buffer.set(new StringBuffer("failedFuture-test-buffer-1"));
Label.set("failedFuture-test-label");
CompletableFuture<Character> stage1 = executor.failedFuture(new CharConversionException("A fake exception created by the test"));
Assert.assertTrue(stage1.isDone(),
"Future created by failedFuture is not complete.");
Assert.assertTrue(stage1.isCompletedExceptionally(),
"Future created by failedFuture does not report exceptional completion.");
try {
Character result = stage1.getNow('1');
Assert.fail("Failed future must raise exception. Instead, getNow returned: " + result);
}
catch (CompletionException x) {
if (x.getCause() == null || !(x.getCause() instanceof CharConversionException)
|| !"A fake exception created by the test".equals(x.getCause().getMessage())) {
throw x;
}
}
Buffer.set(new StringBuffer("failedFuture-test-buffer-B"));
CompletableFuture<Character> stage2a = stage1.exceptionally(x -> {
Assert.assertEquals(x.getClass(), CharConversionException.class,
"Wrong exception class supplied to 'exceptionally' method.");