/
ThreadContextTest.java
1308 lines (1076 loc) · 62 KB
/
ThreadContextTest.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 static org.eclipse.microprofile.concurrency.tck.contexts.priority.spi.ThreadPriorityContextProvider.THREAD_PRIORITY;
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.function.Supplier;
import javax.naming.InitialContext;
import javax.naming.NamingException;
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 ThreadContextTest 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 fake 'ThreadPriority' context type
JavaArchive threadPriorityContextProvider = ShrinkWrap.create(JavaArchive.class, "threadPriorityContext.jar")
.addPackage("org.eclipse.microprofile.concurrency.tck.contexts.priority.spi")
.addAsServiceProvider(ThreadContextProvider.class, ThreadPriorityContextProvider.class);
// build a JAR that provides two fake context types: 'Buffer' and 'Label'
JavaArchive multiContextProvider = ShrinkWrap.create(JavaArchive.class, "bufferAndLabelContext.jar")
.addPackages(true, "org.eclipse.microprofile.concurrency.tck.contexts.buffer")
.addPackages(true, "org.eclipse.microprofile.concurrency.tck.contexts.label")
.addAsServiceProvider(ThreadContextProvider.class, BufferContextProvider.class, LabelContextProvider.class);
return ShrinkWrap.create(WebArchive.class, ThreadContextTest.class.getSimpleName() + ".war")
.addClass(ThreadContextTest.class)
.addAsLibraries(threadPriorityContextProvider, multiContextProvider);
}
@Test
public void builderForThreadContextIsProvided() {
Assert.assertNotNull(ThreadContext.builder(),
"MicroProfile Concurrency implementation does not provide a ThreadContext builder.");
}
/**
* Verify that if JTA transactions are supported, then configuring cleared=TRANSACTION
* results in the active transaction being suspended before running a task and resumed afterward,
* such that a task can use its own transactions if so desired.
*/
@Test
public void clearTransactionContextJTA() throws Exception {
Class<?> userTransaction;
try {
userTransaction = Class.forName("javax.transaction.UserTransaction");
}
catch (ClassNotFoundException x) {
System.out.println("Skipping test clearTransactionContextJTA. javax.transaction.UserTransaction class not available to applications.");
return;
}
Object txFromJNDI = null;
try {
txFromJNDI = InitialContext.doLookup("java:comp/UserTransaction");
System.out.println("JTA UserTransaction is available in JNDI.");
}
catch (NamingException x) {
System.out.println("JTA UserTransaction not available in JNDI: " + x);
}
Object txFromCDI = null;
try {
// txFromCDI = CDI.current().select(UserTransaction.class).get();
Class<?> cdi = Class.forName("javax.enterprise.inject.spi.CDI");
Object current = cdi.getMethod("current").invoke(null);
Object instance = cdi.getMethod("select", Class.class, Annotation[].class).invoke(current, userTransaction, new Annotation[] {});
txFromCDI = instance.getClass().getMethod("get").invoke(instance);
System.out.println("JTA UserTransaction is available via CDI.");
}
catch (RuntimeException | InvocationTargetException x) {
System.out.println("JTA UserTransaction not available via CDI: " +
(x instanceof InvocationTargetException ? x.getCause() : x));
}
Object tx = txFromJNDI == null ? txFromCDI : txFromJNDI;
if (tx == null) {
System.out.println("Skipping test clearTransactionContextJTA. JTA transactions are not supported.");
return;
}
System.out.println("Using JTA UserTransaction: " + tx);
Method begin = userTransaction.getMethod("begin");
Method commit = userTransaction.getMethod("commit");
Method getStatus = userTransaction.getMethod("getStatus");
ThreadContext threadContext = ThreadContext.builder()
.cleared(ThreadContext.TRANSACTION)
.build();
Callable<String> taskWithNewTransaction = threadContext.contextualCallable(() -> {
Assert.assertEquals(getStatus.invoke(tx), 6, // javax.transaction.Status.STATUS_NO_TRANSACTION
"Transaction status should indicate no transaction is active on thread.");
begin.invoke(tx);
commit.invoke(tx);
return "SUCCESS";
});
begin.invoke(tx);
try {
Assert.assertEquals(taskWithNewTransaction.call(), "SUCCESS");
Assert.assertEquals(getStatus.invoke(tx), 0, // javax.transaction.Status.STATUS_ACTIVE
"Transaction status should indicate active transaction on thread.");
}
finally {
commit.invoke(tx);
}
}
/**
* Verify that the MicroProfile Concurrency ThreadContext implementation clears context
* types that are not configured under propagated, unchanged, or cleared.
* @throws Exception
*/
@Test
public void clearUnspecifiedContexts() throws Exception {
ThreadContext threadContext = ThreadContext.builder()
.propagated(Buffer.CONTEXT_NAME)
.unchanged(Label.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"));
Label.set("clearUnspecifiedContexts-test-label-A");
Callable<Integer> callable = threadContext.contextualCallable(() -> {
Assert.assertEquals(Buffer.get().toString(), "clearUnspecifiedContexts-test-buffer-A",
"Context type was not propagated to contextual action.");
Assert.assertEquals(Label.get(), "clearUnspecifiedContexts-test-label-C",
"Context type was not left unchanged by contextual action.");
Buffer.set(new StringBuffer("clearUnspecifiedContexts-test-buffer-B"));
Label.set("clearUnspecifiedContexts-test-label-B");
return Thread.currentThread().getPriority();
});
Buffer.set(new StringBuffer("clearUnspecifiedContexts-test-buffer-C"));
Label.set("clearUnspecifiedContexts-test-label-C");
Assert.assertEquals(callable.call(), Integer.valueOf(Thread.NORM_PRIORITY),
"Context type that remained unspecified was not cleared by default.");
Assert.assertEquals(Buffer.get().toString(), "clearUnspecifiedContexts-test-buffer-C",
"Previous context (Buffer) was not restored after context was propagated for contextual action.");
Assert.assertEquals(Label.get(), "clearUnspecifiedContexts-test-label-B",
"Context type was not left unchanged by contextual action.");
}
finally {
// Restore original values
Buffer.set(null);
Label.set(null);
Thread.currentThread().setPriority(originalPriority);
}
}
/**
* Verify that the MicroProfile Concurrency ThreadContext implementation's contextualConsumer
* method can be used to wrap a BiConsumer instance with the context that is captured from the
* current thread per the configuration of the ThreadContext builder, and that the context is
* applied when the BiConsumer accept method runs. This test case aligns with use case of
* supplying a contextual BiConsumer to a completion stage that is otherwise not context-aware.
*/
@Test
public void contextualBiConsumerRunsWithContext() throws InterruptedException {
ThreadContext bufferContext = ThreadContext.builder()
.propagated(Buffer.CONTEXT_NAME)
.cleared(ThreadContext.ALL_REMAINING)
.build();
try {
// Set non-default values
Buffer.get().append("contextualBiConsumer-test-buffer");
Label.set("contextualBiConsumer-test-label");
// To avoid the possibility that CompletableFuture.get might cause the action to run
// on the current thread, which would bypass the intent of testing context propagation,
// use a countdown latch to independently wait for completion.
CountDownLatch completed = new CountDownLatch(1);
// CompletableFuture from Java SE is intentionally used here to avoid the context
// propagation guarantees of MicroProfile Concurrency's ManagedExecutor.
// This ensures we are testing that MicroProfile Concurrency's ThreadContext is
// doing the work to propagate the context rather than getting it from a
// ManagedExecutor.
CompletableFuture<String> stage1a = CompletableFuture.supplyAsync(() -> "supplied-value-A");
CompletableFuture<String> stage1b = CompletableFuture.supplyAsync(() -> "supplied-value-B");
CompletableFuture<Void> stage2 = stage1a.thenAcceptBothAsync(stage1b,
bufferContext.contextualConsumer((a, b) -> {
Assert.assertEquals(a, "supplied-value-A",
"First value supplied to BiConsumer was lost or altered.");
Assert.assertEquals(b, "supplied-value-B",
"Second value supplied to BiConsumer was lost or altered.");
Assert.assertEquals(Buffer.get().toString(), "contextualBiConsumer-test-buffer",
"Context type was not propagated to contextual action.");
Assert.assertEquals(Label.get(), "",
"Context type that is configured to be cleared was not cleared.");
}),
unmanagedThreads);
stage2.whenComplete((unused, failure) -> completed.countDown());
Assert.assertTrue(completed.await(MAX_WAIT_NS, TimeUnit.NANOSECONDS),
"Completable future did not finish in a reasonable amount of time.");
// Force errors, if any, to be reported
stage2.join();
}
finally {
// Restore original values
Buffer.set(null);
Label.set(null);
}
}
/**
* Verify that the MicroProfile Concurrency ThreadContext implementation's contextualFunction
* method can be used to wrap a BiFunction instance with the context that is captured from the
* current thread per the configuration of the ThreadContext builder, and that the context is
* applied when the BiFunction apply method runs. This test case aligns with use case of
* supplying a contextual BiFunction to a completion stage that is otherwise not context-aware.
*/
@Test
public void contextualBiFunctionRunsWithContext()
throws ExecutionException, InterruptedException, TimeoutException {
ThreadContext labelContext = ThreadContext.builder()
.propagated(Label.CONTEXT_NAME)
.build();
try {
// Set non-default values
Buffer.get().append("contextualBiFunction-test-buffer");
Label.set("contextualBiFunction-test-label");
// CompletableFuture from Java SE is intentionally used here to avoid the context
// propagation guarantees of MicroProfile Concurrency's ManagedExecutor.
// This ensures we are testing that MicroProfile Concurrency's ThreadContext is
// doing the work to propagate the context rather than getting it from a
// ManagedExecutor.
CompletableFuture<Integer> stage1a = new CompletableFuture<Integer>();
CompletableFuture<Integer> stage1b = new CompletableFuture<Integer>();
CompletableFuture<Integer> stage2 = stage1a.thenCombine(stage1b,
labelContext.contextualFunction((a, b) -> {
Assert.assertEquals(a, Integer.valueOf(10),
"First value supplied to BiFunction was lost or altered.");
Assert.assertEquals(b, Integer.valueOf(20),
"Second value supplied to BiFunction was lost or altered.");
Assert.assertEquals(Label.get(), "contextualBiFunction-test-label",
"Context type was not propagated to contextual action.");
Assert.assertEquals(Buffer.get().toString(), "",
"Context type that is configured to be cleared was not cleared.");
return a + b;
}));
Future<Integer> future = unmanagedThreads.submit(() -> {
stage1a.complete(10);
stage1b.complete(20);
return stage2.get(MAX_WAIT_NS, TimeUnit.NANOSECONDS);
});
Assert.assertEquals(future.get(MAX_WAIT_NS, TimeUnit.NANOSECONDS), Integer.valueOf(30),
"Result of BiFunction was lost or altered.");
}
finally {
// Restore original values
Buffer.set(null);
Label.set(null);
}
}
/**
* Verify that the MicroProfile Concurrency ThreadContext implementation's contextualCallable
* method can be used to wrap a Callable instance with the context that is captured from the
* current thread per the configuration of the ThreadContext builder, and that the context is
* applied when the Callable call method runs. This test case aligns with use case of
* supplying a contextual Callable to an unmanaged executor that is otherwise not context-aware.
*/
@Test
public void contextualCallableRunsWithContext()
throws ExecutionException, InterruptedException, TimeoutException {
ThreadContext priorityContext = ThreadContext.builder()
.propagated(THREAD_PRIORITY)
.build();
int originalPriority = Thread.currentThread().getPriority();
try {
// Set non-default values
int newPriority = originalPriority == 4 ? 3 : 4;
Thread.currentThread().setPriority(newPriority);
Buffer.get().append("contextualCallable-test-buffer");
Label.set("contextualCallable-test-label");
Future<Integer> future = unmanagedThreads.submit(priorityContext.contextualCallable(() -> {
Assert.assertEquals(Buffer.get().toString(), "",
"Context type (Buffer) that is configured to be cleared was not cleared.");
Assert.assertEquals(Label.get(), "",
"Context type (Label) that is configured to be cleared was not cleared.");
return Thread.currentThread().getPriority();
}));
Assert.assertEquals(future.get(MAX_WAIT_NS, TimeUnit.NANOSECONDS), Integer.valueOf(newPriority),
"Callable returned incorrect value.");
}
finally {
// Restore original values
Buffer.set(null);
Label.set(null);
Thread.currentThread().setPriority(originalPriority);
}
}
/**
* Verify that the MicroProfile Concurrency ThreadContext implementation's contextualConsumer
* method can be used to wrap a Consumer instance with the context that is captured from the
* current thread per the configuration of the ThreadContext builder, and that the context is
* applied when the Consumer accept method runs. This test case aligns with use case of
* supplying a contextual Consumer to a completion stage that is otherwise not context-aware.
*/
@Test
public void contextualConsumerRunsWithContext() throws InterruptedException {
ThreadContext labelContext = ThreadContext.builder()
.propagated(Label.CONTEXT_NAME)
.build();
try {
// Set non-default values
Buffer.get().append("contextualConsumer-test-buffer");
Label.set("contextualConsumer-test-label");
// To avoid the possibility that CompletableFuture.get might cause the action to run
// on the current thread, which would bypass the intent of testing context propagation,
// use a countdown latch to independently wait for completion.
CountDownLatch completed = new CountDownLatch(1);
// Similarly, the initial stage is left incomplete until after thenAccept adds the
// action, to eliminate the possibility that this triggers the action to run inline.
// CompletableFuture from Java SE is intentionally used here to avoid the context
// propagation guarantees of MicroProfile Concurrency's ManagedExecutor.
// This ensures we are testing that MicroProfile Concurrency's ThreadContext is
// doing the work to propagate the context rather than getting it from a
// ManagedExecutor.
CompletableFuture<String> stage1 = new CompletableFuture<String>();
CompletableFuture<Void> stage2 = stage1
.thenApplyAsync(unused -> "supply-to-consumer", unmanagedThreads)
.thenAccept(labelContext.contextualConsumer(s -> {
Assert.assertEquals(s, "supply-to-consumer",
"Value supplied to Consumer was lost or altered.");
Assert.assertEquals(Buffer.get().toString(), "",
"Context type that is configured to be cleared was not cleared.");
Assert.assertEquals(Label.get(), "contextualConsumer-test-label",
"Context type was not propagated to contextual action.");
}));
stage1.complete("unblock");
stage2.whenComplete((unused, failure) -> completed.countDown());
Assert.assertTrue(completed.await(MAX_WAIT_NS, TimeUnit.NANOSECONDS),
"Completable future did not finish in a reasonable amount of time.");
// Force errors, if any, to be reported
stage2.join();
}
finally {
// Restore original values
Buffer.set(null);
Label.set(null);
}
}
/**
* Verify that the MicroProfile Concurrency ThreadContext implementation's contextualFunction
* method can be used to wrap a Function instance with the context that is captured from the
* current thread per the configuration of the ThreadContext builder, and that the context is
* applied when the Function apply method runs. This test case aligns with use case of
* supplying a contextual Function to a completion stage that is otherwise not context-aware.
*/
@Test
public void contextualFunctionRunsWithContext()
throws ExecutionException, InterruptedException, TimeoutException {
ThreadContext bufferContext = ThreadContext.builder()
.propagated(Buffer.CONTEXT_NAME)
.build();
try {
// Set non-default values
Buffer.get().append("contextualFunction-test-buffer");
Label.set("contextualFunction-test-label");
// Reusable contextual function
Function<Long, Long> contextualFunction = bufferContext.contextualFunction(i -> {
Buffer.get().append("-" + i);
Assert.assertEquals(Label.get(), "",
"Context type that is configured to be cleared was not cleared.");
return i * 2L;
});
// CompletableFuture from Java SE is intentionally used here to avoid the context
// propagation guarantees of MicroProfile Concurrency's ManagedExecutor.
// This ensures we are testing that MicroProfile Concurrency's ThreadContext is
// doing the work to propagate the context rather than getting it from a
// ManagedExecutor.
CompletableFuture<Long> stage1 = new CompletableFuture<Long>();
CompletableFuture<Long> stage2 = stage1
.thenApply(contextualFunction)
.thenApply(i -> i + 10)
.thenApply(contextualFunction);
Future<Long> future = unmanagedThreads.submit(() -> {
stage1.complete(75L);
return stage2.get(MAX_WAIT_NS, TimeUnit.NANOSECONDS);
});
Assert.assertEquals(future.get(MAX_WAIT_NS, TimeUnit.NANOSECONDS), Long.valueOf(320),
"Result of Function was lost or altered.");
// Verify updates written to the 'buffer' context from the contextual actions
Assert.assertEquals(Buffer.get().toString(), "contextualFunction-test-buffer-75-160",
"Context not propagated or incorrectly propagated to contextualFunctions.");
}
finally {
// Restore original values
Buffer.set(null);
Label.set(null);
}
}
/**
* Verify that the MicroProfile Concurrency ThreadContext implementation's contextualRunnable
* method can be used to wrap a Runnable instance with the context that is captured from the
* current thread per the configuration of the ThreadContext builder, and that the context is
* applied when the Runnable run method runs. This test case aligns with use case of
* supplying a contextual Runnable to a completion stage that is otherwise not context-aware.
*/
@Test
public void contextualRunnableRunsWithContext()
throws ExecutionException, InterruptedException, TimeoutException {
ThreadContext priorityAndBufferContext = ThreadContext.builder()
.propagated(THREAD_PRIORITY, Buffer.CONTEXT_NAME)
.build();
int originalPriority = Thread.currentThread().getPriority();
try {
// Set non-default values
int newPriority = originalPriority == 2 ? 1 : 2;
Thread.currentThread().setPriority(newPriority);
Buffer.get().append("contextualRunnable-test-buffer");
Label.set("contextualRunnable-test-label");
// Reusable contextual Runnable
Runnable contextualRunnable = priorityAndBufferContext.contextualRunnable(() -> {
int priority = Thread.currentThread().getPriority();
Buffer.get().append("-" + priority);
Assert.assertEquals(Label.get(), "",
"Context type that is configured to be cleared was not cleared.");
});
Thread.currentThread().setPriority(originalPriority);
// CompletableFuture from Java SE is intentionally used here to avoid the context
// propagation guarantees of MicroProfile Concurrency's ManagedExecutor.
// This ensures we are testing that MicroProfile Concurrency's ThreadContext is
// doing the work to propagate the context rather than getting it from a
// ManagedExecutor.
CompletableFuture<Void> stage1 = new CompletableFuture<Void>();
CompletableFuture<Void> stage2 = stage1
.thenRun(contextualRunnable)
.thenRun(() -> Buffer.get().append("-non-contextual-runnable"))
.thenRun(contextualRunnable);
Future<Void> future = unmanagedThreads.submit(() -> {
stage1.complete(null);
stage2.get(MAX_WAIT_NS, TimeUnit.NANOSECONDS);
return null;
});
future.get(MAX_WAIT_NS, TimeUnit.NANOSECONDS);
// Verify updates written to the 'buffer' context from the contextual actions
Assert.assertEquals(Buffer.get().toString(), "contextualRunnable-test-buffer-" + newPriority + "-" + newPriority,
"Context not propagated or incorrectly propagated to contextualFunctions.");
}
finally {
// Restore original values
Thread.currentThread().setPriority(originalPriority);
Buffer.set(null);
Label.set(null);
}
}
/**
* Verify that the MicroProfile Concurrency ThreadContext implementation's contextualSupplier
* method can be used to wrap a Supplier instance with the context that is captured from the
* current thread per the configuration of the ThreadContext builder, and that the context is
* applied when the Supplier get method runs. This test case aligns with use case of
* supplying a contextual Supplier to a completion stage that is otherwise not context-aware.
*/
@Test
public void contextualSupplierRunsWithContext() throws InterruptedException {
ThreadContext bufferContext = ThreadContext.builder()
.propagated(Buffer.CONTEXT_NAME)
.unchanged(ThreadContext.APPLICATION)
.build();
try {
// Set non-default values
Buffer.get().append("contextualSupplier-test-buffer");
Label.set("contextualSupplier-test-label");
// To avoid the possibility that CompletableFuture.get might cause the action to run
// on the current thread, which would bypass the intent of testing context propagation,
// use a countdown latch to independently wait for completion.
CountDownLatch completed = new CountDownLatch(1);
// CompletableFuture from Java SE is intentionally used here to avoid the context
// propagation guarantees of MicroProfile Concurrency's ManagedExecutor.
// This ensures we are testing that MicroProfile Concurrency's ThreadContext is
// doing the work to propagate the context rather than getting it from a
// ManagedExecutor.
CompletableFuture<String> stage1 = CompletableFuture.supplyAsync(
bufferContext.contextualSupplier(() -> {
Assert.assertEquals(Label.get(), "",
"Context type that is configured to be cleared was not cleared.");
String bufferContents = Buffer.get().toString();
Assert.assertEquals(bufferContents, "contextualSupplier-test-buffer",
"Context type was not propagated to contextual action.");
return bufferContents;
}));
stage1.whenComplete((unused, failure) -> completed.countDown());
Assert.assertTrue(completed.await(MAX_WAIT_NS, TimeUnit.NANOSECONDS),
"Completable future did not finish in a reasonable amount of time.");
// Force errors, if any, to be reported
String result = stage1.join();
Assert.assertEquals(result, "contextualSupplier-test-buffer",
"Supplier result was lost or altered.");
}
finally {
// Restore original values
Buffer.set(null);
Label.set(null);
}
}
/**
* Verify that the ThreadContext.Builder can be used to create multiple ThreadContexts with
* different configured contexts.
* @throws Exception
*/
@Test
public void reuseThreadContextBuilder() throws Exception {
ThreadContext.Builder builder = ThreadContext.builder()
.propagated()
.cleared(Buffer.CONTEXT_NAME, THREAD_PRIORITY);
ThreadContext clearingContext = builder.build();
ThreadContext propagatingContext = builder.propagated(Buffer.CONTEXT_NAME, THREAD_PRIORITY)
.cleared()
.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("reuseBuilder-test-buffer-A"));
Callable<Integer> clearedCallable = clearingContext.contextualCallable(() -> {
Assert.assertEquals(Buffer.get().toString(), "",
"Context type that is configured to be cleared was not cleared.");
Buffer.set(new StringBuffer("reuseBuilder-test-buffer-B"));
return Thread.currentThread().getPriority();
});
Callable<Integer> propagatedCallable = propagatingContext.contextualCallable(() -> {
Assert.assertEquals(Buffer.get().toString(), "reuseBuilder-test-buffer-A",
"Context type was not propagated to contextual action.");
Buffer.set(new StringBuffer("reuseBuilder-test-buffer-C"));
return Thread.currentThread().getPriority();
});
Buffer.set(new StringBuffer("reuseBuilder-test-buffer-D"));
Thread.currentThread().setPriority(newPriority - 1);
Assert.assertEquals(propagatedCallable.call(), Integer.valueOf(newPriority),
"Context type was not propagated to contextual action.");
Assert.assertEquals(clearedCallable.call(), Integer.valueOf(Thread.NORM_PRIORITY),
"Context type that is configured to be cleared was not cleared.");
Assert.assertEquals(Buffer.get().toString(), "reuseBuilder-test-buffer-D",
"Previous context (Buffer) was not restored after context was propagated for contextual action.");
}
finally {
// Restore original values
Buffer.set(null);
Thread.currentThread().setPriority(originalPriority);
}
}
/**
* Verify that the MicroProfile Concurrency implementation finds third-party thread context providers
* that are made available to the ServiceLoader, allows their configuration via the ThreadContext builder,
* and correctly captures & propagates or clears these thread context types per the builder configuration.
* Subsequently verify that the MicroProfile Concurrency implementation properly restores thread context
* after the contextual action completes.
*/
@Test
public void thirdPartyContextProvidersAreIncludedInThreadContext() {
ThreadContext labelAndPriorityContext = ThreadContext.builder()
.propagated(THREAD_PRIORITY, Label.CONTEXT_NAME)
.cleared(Buffer.CONTEXT_NAME)
.unchanged(ThreadContext.ALL_REMAINING)
.build();
int originalPriority = Thread.currentThread().getPriority();
int priorityA = originalPriority == 3 ? 2 : 3; // a non-default value
int priorityB = priorityA - 1; // a different non-default value
try {
// Set non-default values
Buffer.get().append("test-buffer-content-A");
Label.set("test-label-A");
Thread.currentThread().setPriority(priorityA);
Supplier<Integer> contextualSupplier = labelAndPriorityContext.contextualSupplier(() -> {
Assert.assertEquals(Buffer.get().toString(), "", "Context type that is configured to be cleared was not cleared.");
Assert.assertEquals(Label.get(), "test-label-A", "Context type was not propagated to contextual action.");
return Thread.currentThread().getPriority();
});
// Alter the values again
Buffer.get().append("-and-B");
Label.set("test-label-B");
Thread.currentThread().setPriority(priorityB);
// The contextual action runs with previously captured Label/ThreadPriority context, and with cleared Buffer context
int priority = contextualSupplier.get();
Assert.assertEquals(priority, priorityA, "Context type was not propagated to contextual action.");
// The contextual action and its associated thread context snapshot is reusable
priority = contextualSupplier.get();
Assert.assertEquals(priority, priorityA, "Context type was not propagated to contextual action.");
// Has context been properly restored after the contextual operation(s)?
Assert.assertEquals(Buffer.get().toString(), "test-buffer-content-A-and-B",
"Previous context was not restored after context was cleared for contextual action.");
Assert.assertEquals(Label.get(), "test-label-B",
"Previous context (Label) was not restored after context was propagated for contextual action.");
Assert.assertEquals(Thread.currentThread().getPriority(), priorityB,
"Previous context (ThreadPriority) was not restored after context was propagated for contextual action.");
}
finally {
// Restore original values
Buffer.set(null);
Label.set(null);
Thread.currentThread().setPriority(originalPriority);
}
}
/**
* Verify that the MicroProfile Concurrency ThreadContext implementation's withContextCapture
* method can be used to create a dependent CompletableFuture instance that completes when the
* original stage completes and runs dependent stage actions with context that is captured
* from the thread that creates the dependent stage.
*/
@Test
public void withContextCaptureDependentCompletableFuturesRunWithContext()
throws ExecutionException, InterruptedException, TimeoutException {
ThreadContext labelContext = ThreadContext.builder()
.propagated(Label.CONTEXT_NAME)
.cleared(ThreadContext.ALL_REMAINING)
.build();
ManagedExecutor bufferContextExecutor = ManagedExecutor.builder()
.propagated(Buffer.CONTEXT_NAME)
.cleared(ThreadContext.ALL_REMAINING)
.build();
long testThreadId = Thread.currentThread().getId();
try {
// Set non-default values
Buffer.get().append("withContextCapture-CompletableFuture-test-buffer");
Label.set("withContextCapture-CompletableFuture-test-label-A");
CompletableFuture<Integer> unmanagedStage1 = new CompletableFuture<Integer>();
CompletableFuture<Integer> stage2 = labelContext.withContextCapture(unmanagedStage1);
CompletableFuture<Integer> stage3 = stage2.thenApply(i -> {
Assert.assertEquals(i, Integer.valueOf(1010),
"Value supplied to function does not match the value with which the dependent stage was completed.");
Assert.assertEquals(Label.get(), "withContextCapture-CompletableFuture-test-label-A",
"Context type was not propagated to contextual action.");
Assert.assertEquals(Buffer.get().toString(), "",
"Context type that is configured to be cleared was not cleared.");
Assert.assertEquals(Thread.currentThread().getId(), testThreadId,
"Completion stages created via withContextCapture must run on the test case's main thread " +
"because it both completes the original stage and requests the result.");
Label.set("withContextCapture-CompletableFuture-test-label-B");
return i * 2;
});
Label.set("withContextCapture-CompletableFuture-test-label-C");
CompletableFuture<Integer> stage4 = stage3.thenApplyAsync(i -> {
Assert.assertEquals(i, Integer.valueOf(2020),
"Incorrect value supplied to function.");
Assert.assertEquals(Label.get(), "withContextCapture-CompletableFuture-test-label-C",
"Context type was not propagated to contextual action.");
Assert.assertEquals(Buffer.get().toString(), "",
"Context type that is configured to be cleared was not cleared.");
Label.set("withContextCapture-CompletableFuture-test-label-D");
return i + i;
}, bufferContextExecutor); // supplied executor runs the action, but does not determine context propagation
// Original stage remains usable, but not having been created by a ManagedExecutor, does not make any
// guarantees about context propagation
CompletableFuture<Integer> unmanagedStage5 = unmanagedStage1.thenApply(i -> i / 2);
try {
CompletableFuture<Integer> stage6 = stage4.thenApplyAsync(i -> i / 5);
Assert.fail("Should not be able to create async completion stage because withContextCapture provides no executor. " + stage6);
}
catch (UnsupportedOperationException x) {
// test passes, CompletableFutures from withContextCapture are not backed by an executor
}
Label.set("withContextCapture-CompletableFuture-test-label-E");
unmanagedStage1.complete(1010);
Assert.assertEquals(stage2.getNow(9090), Integer.valueOf(1010),
"Completion stage created by withContextCapture did not complete with same value as original stage.");
Assert.assertEquals(stage3.get(MAX_WAIT_NS, TimeUnit.NANOSECONDS), Integer.valueOf(2020),
"Incorrect or missing result of completion stage.");
Assert.assertEquals(stage4.join(), Integer.valueOf(4040),
"Incorrect or missing result of completion stage.");
Assert.assertEquals(unmanagedStage5.get(), Integer.valueOf(505),
"Incorrect or missing result of completion stage.");
// Has context been properly restored after the contextual operation(s)?
Assert.assertEquals(Buffer.get().toString(), "withContextCapture-CompletableFuture-test-buffer",
"Previous context was not restored after context was cleared for contextual action.");
Assert.assertEquals(Label.get(), "withContextCapture-CompletableFuture-test-label-E",
"Previous context was not restored after context was propagated for contextual action.");
}
finally {
bufferContextExecutor.shutdownNow();
// Restore original values
Buffer.set(null);
Label.set(null);
}
}
/**
* Verify that the MicroProfile Concurrency ThreadContext implementation's withContextCapture
* method can be used to create a dependent CompletionStage instance that completes when the
* original stage completes and runs dependent stage actions with context that is captured
* from the thread that creates the dependent stage.
*/
@Test
public void withContextCaptureDependentCompletionStagesRunWithContext() throws ExecutionException, InterruptedException, TimeoutException {
ThreadContext bufferContext = ThreadContext.builder()
.propagated(Buffer.CONTEXT_NAME)
.cleared(ThreadContext.ALL_REMAINING)
.build();
ManagedExecutor labelContextExecutor = ManagedExecutor.builder()
.propagated(Label.CONTEXT_NAME)
.cleared(ThreadContext.ALL_REMAINING)
.build();
long testThreadId = Thread.currentThread().getId();
try {
// Set non-default values
StringBuffer buffer = new StringBuffer("withContextCapture-CompletionStage-test-buffer-A");
Buffer.set(buffer);
Label.set("withContextCapture-CompletionStage-test-label");
CompletableFuture<Integer> unmanagedStage1 = new CompletableFuture<Integer>();
CompletionStage<Integer> stage2 = bufferContext.withContextCapture((CompletionStage<Integer>) unmanagedStage1);
if (stage2 instanceof CompletableFuture) {
try {
((CompletableFuture<Integer>) stage2).complete(4321);
Assert.fail("Must not be possible to forcibly complete the CompletionStage that is returned by the variant" +
"of withContextCapture that accepts and returns a CompletionStage rather than CompletableFuture.");
}
catch (UnsupportedOperationException x) {
// test passes - this matches behavior of Java SE minimalCompletionStage, which implements
// CompletableFuture, but rejects methods that perform completion.
}
}
CompletionStage<Integer> stage3 = stage2.thenApply(i -> {
Assert.assertEquals(i, Integer.valueOf(1234),
"Value supplied to function does not match the value with which the dependent stage was completed.");
Assert.assertEquals(Buffer.get().toString(), "withContextCapture-CompletionStage-test-buffer-A",
"Context type was not propagated to contextual action.");
Assert.assertEquals(Label.get().toString(), "",
"Context type that is configured to be cleared was not cleared.");
Assert.assertEquals(Thread.currentThread().getId(), testThreadId,
"Completion stages created via withContextCapture must run on the test case's main thread " +
"because it both completes the original stage and requests the result.");
Buffer.get().append("-stage3");
Buffer.set(new StringBuffer("withContextCapture-CompletionStage-test-buffer-B"));
return i * 2;
});
CompletionStage<Integer> stage4 = stage3.thenApplyAsync(i -> {
Assert.assertEquals(i, Integer.valueOf(2468),
"Incorrect value supplied to function.");
Assert.assertEquals(Buffer.get().toString(), "withContextCapture-CompletionStage-test-buffer-A-stage3",
"Context type was not propagated to contextual action.");
Assert.assertEquals(Label.get(), "",
"Context type that is configured to be cleared was not cleared.");
Buffer.get().append("-stage4");
Buffer.set(new StringBuffer("withContextCapture-CompletionStage-test-buffer-D"));
return i - 2345;
}, labelContextExecutor); // supplied executor runs the action, but does not determine context propagation
try {
CompletionStage<Void> stage5 = stage4.thenAcceptAsync(i -> System.out.println("This should not ever run."));
Assert.fail("Should not be able to create async completion stage because withContextCapture provides no executor. " + stage5);
}
catch (UnsupportedOperationException x) {
// test passes, CompletableFutures from withContextCapture are not backed by an executor
}
Buffer.set(new StringBuffer("withContextCapture-CompletionStage-test-buffer-E"));
unmanagedStage1.complete(1234);
CompletableFuture<Integer> cf4 = stage4.toCompletableFuture();
Assert.assertEquals(cf4.get(MAX_WAIT_NS, TimeUnit.NANOSECONDS), Integer.valueOf(123),
"Completion stage created by withContextCapture did not complete with same value as original stage.");
Assert.assertEquals(buffer.toString(), "withContextCapture-CompletionStage-test-buffer-A-stage3-stage4");
// Has context been properly restored after the contextual operation(s)?
Assert.assertEquals(Buffer.get().toString(), "withContextCapture-CompletionStage-test-buffer-E",
"Previous context was not restored after context was propagated for contextual action.");
Assert.assertEquals(Label.get(), "withContextCapture-CompletionStage-test-label",
"Previous context was not restored after context was cleared for contextual action.");
}
finally {
labelContextExecutor.shutdownNow();
// Restore original values
Buffer.set(null);