-
Notifications
You must be signed in to change notification settings - Fork 23
/
MPConfigTest.java
645 lines (539 loc) · 30.9 KB
/
MPConfigTest.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
/*
* Copyright (c) 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.lang.reflect.Method;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.Future;
import java.util.concurrent.Phaser;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import javax.inject.Inject;
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.NamedInstance;
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.AfterMethod;
import org.testng.annotations.BeforeMethod;
public class MPConfigTest 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);
@Inject
protected MPConfigBean bean;
@Inject @NamedInstance("namedExecutor")
protected ManagedExecutor namedExecutor;
@Inject @NamedInstance("namedThreadContext")
protected ThreadContext namedThreadContext;
@Inject @NamedInstance("producedExecutor")
protected ManagedExecutor producedExecutor;
@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);
}
}
@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, MPConfigTest.class.getSimpleName() + ".war")
.addClass(MPConfigBean.class)
.addClass(MPConfigTest.class)
.addAsManifestResource("META-INF/microprofile-config.properties", "microprofile-config.properties")
.addAsLibraries(fakeContextProviders);
}
/**
* Determine if instances injected properly, which is a prerequisite of running these tests.
*/
@Test
public void beanInjected() {
Assert.assertNotNull(bean,
"Unable to inject CDI bean. Expect other tests to fail.");
}
/**
* Verify that MicroProfile config overrides the cleared and propagated attributes
* of a ManagedExecutor that is produced by the container because the application annotated
* an unqualified injection point with ManagedExecutorConfig.
*/
@Test(dependsOnMethods = "beanInjected")
public void overrideContextPropagationForManagedExecutorFieldWithConfig()
throws ExecutionException, InterruptedException, TimeoutException {
// Expected config is maxAsync=2; maxQueued=3; propagated=Label; cleared=Remaining
ManagedExecutor executor = bean.getExecutorWithConfig();
Assert.assertNotNull(executor,
"Unable to inject ManagedExecutor with ManagedExecutorConfig. Cannot run test.");
int originalPriority = Thread.currentThread().getPriority();
try {
// Set non-default values
int newPriority = originalPriority == 3 ? 2 : 3;
Thread.currentThread().setPriority(newPriority);
Buffer.set(new StringBuffer("overrideMangedExecutorConfig-test-buffer"));
Label.set("overrideMangedExecutorConfig-test-label");
// Run on separate thread to test propagated
CompletableFuture<Void> stage1 = namedExecutor.runAsync(() ->
Assert.assertEquals(Label.get(), "overrideMangedExecutorConfig-test-label",
"Context type that MicroProfile config overrides to be propagated was not correctly propagated.")
);
Assert.assertNull(stage1.get(MAX_WAIT_NS, TimeUnit.NANOSECONDS),
"Non-null value returned by stage that runs Runnable async.");
// Run on current thread to test cleared
CompletableFuture<Void> stage2 = stage1.thenRun(() -> {
Assert.assertEquals(Buffer.get().toString(), "",
"Context type (Buffer) that MicroProfile config overrides to be cleared was not cleared.");
Assert.assertEquals(Thread.currentThread().getPriority(), Thread.NORM_PRIORITY,
"Context type (ThreadPriority) that MicroProfile config overrides to be cleared was not cleared.");
});
Assert.assertNull(stage2.get(MAX_WAIT_NS, TimeUnit.NANOSECONDS),
"Non-null value returned by stage that runs Runnable.");
}
finally {
// Restore original values
Buffer.set(null);
Label.set(null);
Thread.currentThread().setPriority(originalPriority);
}
}
/**
* Verify that MicroProfile config overrides the cleared and propagated attributes
* of a ManagedExecutor that is produced by the container because the application annotated
* an injection point with ManagedExecutorConfig and the NamedInstance qualifier.
*/
@Test(dependsOnMethods = "beanInjected")
public void overrideContextPropagationForManagedExecutorFieldWithConfigAndName()
throws ExecutionException, InterruptedException, TimeoutException {
// Expected config is maxAsync=1, maxQueued=4; cleared=ThreadPriority,Buffer,Transaction; propagated=Remaining
Assert.assertNotNull(namedExecutor,
"Unable to inject ManagedExecutor qualified by NamedInstance. Cannot run test.");
int originalPriority = Thread.currentThread().getPriority();
try {
// Set non-default values
int newPriority = originalPriority == 4 ? 3 : 4;
Thread.currentThread().setPriority(newPriority);
Buffer.set(new StringBuffer("configOverrideCP-test-buffer"));
Label.set("configOverrideCP-test-label");
// Run on separate thread to test propagated
CompletableFuture<Void> stage1 = namedExecutor.runAsync(() ->
Assert.assertEquals(Label.get(), "configOverrideCP-test-label",
"Context type that MicroProfile config overrides to be propagated was not correctly propagated.")
);
Assert.assertNull(stage1.get(MAX_WAIT_NS, TimeUnit.NANOSECONDS),
"Non-null value returned by stage that runs Runnable async.");
// Run on current thread to test cleared
CompletableFuture<Void> stage2 = stage1.thenRun(() -> {
Assert.assertEquals(Buffer.get().toString(), "",
"Context type (Buffer) that MicroProfile config overrides to be cleared was not cleared.");
Assert.assertEquals(Thread.currentThread().getPriority(), Thread.NORM_PRIORITY,
"Context type (ThreadPriority) that MicroProfile config overrides to be cleared was not cleared.");
});
Assert.assertNull(stage2.get(MAX_WAIT_NS, TimeUnit.NANOSECONDS),
"Non-null value returned by stage that runs Runnable.");
}
finally {
// Restore original values
Buffer.set(null);
Label.set(null);
Thread.currentThread().setPriority(originalPriority);
}
}
/**
* Verify that MicroProfile config overrides the cleared and propagated attributes
* of a ManagedExecutor that is produced by the container when the application defines
* a parameter injection point that is neither qualified nor annotated with ManagedExecutorConfig.
*/
@Test(dependsOnMethods = "beanInjected")
public void overrideContextPropagationForManagedExecutorParameter()
throws ExecutionException, InterruptedException, TimeoutException {
// Expected config is maxAsync=1; maxQueued=2; propagated=Buffer,Label; cleared=Remaining
CompletableFuture<Integer> completedFuture = bean.getCompletedFuture();
Assert.assertNotNull(completedFuture,
"Unable to inject ManagedExecutor into method parameter. Cannot run test.");
int originalPriority = Thread.currentThread().getPriority();
try {
// Set non-default values
int newPriority = originalPriority == 2 ? 1 : 2;
Thread.currentThread().setPriority(newPriority);
Buffer.set(new StringBuffer("overrideMangedExecutorConfig-test-buffer"));
Label.set("overrideMangedExecutorConfig-test-label");
// Run on current thread to test cleared
CompletableFuture<Void> stage1 = completedFuture.thenRun(() ->
Assert.assertEquals(Thread.currentThread().getPriority(), Thread.NORM_PRIORITY,
"Context type that MicroProfile config overrides to be cleared was not cleared.")
);
Assert.assertNull(stage1.get(MAX_WAIT_NS, TimeUnit.NANOSECONDS),
"Non-null value returned by stage that runs Runnable.");
// Run on separate thread to test propagated
CompletableFuture<Void> stage2 = completedFuture.thenRunAsync(() -> {
Assert.assertEquals(Label.get(), "overrideMangedExecutorConfig-test-label",
"Context type (Label) that MicroProfile config overrides to be propagated was not correctly propagated.");
Assert.assertEquals(Buffer.get().toString(), "overrideMangedExecutorConfig-test-buffer",
"Context type (Buffer) that MicroProfile config overrides to be propagated was not correctly propagated.");
});
Assert.assertNull(stage2.get(MAX_WAIT_NS, TimeUnit.NANOSECONDS),
"Non-null value returned by stage that runs Runnable async.");
}
finally {
// Restore original values
Buffer.set(null);
Label.set(null);
Thread.currentThread().setPriority(originalPriority);
}
}
/**
* Verify that MicroProfile config overrides the cleared, propagated, and unchanged attributes
* of a ThreadContext that is produced by the container when the application defines
* a field injection point that is neither qualified nor annotated with ThreadContextConfig.
*/
@Test(dependsOnMethods = "beanInjected")
public void overrideContextPropagationForThreadContextField() {
// Expected config is propagated={}; cleared=Buffer,ThreadPriority; unchanged=Remaining
ThreadContext threadContext = bean.getThreadContext();
Assert.assertNotNull(threadContext,
"Unable to inject ThreadContext into field parameter. Cannot run test.");
int originalPriority = Thread.currentThread().getPriority();
try {
// Set non-default values
int newPriority = originalPriority == 3 ? 2 : 3;
Thread.currentThread().setPriority(newPriority);
Buffer.set(new StringBuffer("overrideThreadContext-test-buffer-A"));
Label.set("overrideThreadContext-test-label-A");
Runnable task = threadContext.contextualRunnable(() -> {
Assert.assertEquals(Buffer.get().toString(), "",
"Context type (Buffer) that MicroProfile config overrides to be cleared was not cleared.");
Assert.assertEquals(Thread.currentThread().getPriority(), Thread.NORM_PRIORITY,
"Context type (ThreadPriority) that MicroProfile config overrides to be cleared was not cleared.");
Assert.assertEquals(Label.get(), "overrideThreadContext-test-label-A",
"Context type that MicroProfile config overrides to remain unchanged was changed.");
Label.set("overrideThreadContext-test-label-B");
});
task.run();
Assert.assertEquals(Label.get(), "overrideThreadContext-test-label-B",
"Context type that MicroProfile config overrides to remain unchanged was changed when task completed.");
}
finally {
// Restore original values
Buffer.set(null);
Label.set(null);
Thread.currentThread().setPriority(originalPriority);
}
}
/**
* Verify that MicroProfile config overrides the propagated attributes
* of a ThreadContext that is produced by the container when the application defines
* a field injection point that is annotated with ThreadContextConfig and the NamedInstance qualifier.
*/
@Test(dependsOnMethods = "beanInjected")
public void overrideContextPropagationForThreadContextFieldWithConfigAndName() {
// Expected config is propagated=Label,Buffer; cleared={}, unchanged=Remaining
Assert.assertNotNull(namedThreadContext,
"Unable to inject ThreadContext qualified by NamedInstance. Cannot run test.");
int originalPriority = Thread.currentThread().getPriority();
try {
// Set non-default values
int newPriority = originalPriority == 3 ? 2 : 3;
Thread.currentThread().setPriority(newPriority);
Buffer.set(new StringBuffer("overrideNamedThreadContextConfig-test-buffer-A"));
Label.set("overrideNamedThreadContextConfig-test-label-A");
Consumer<Integer> task = namedThreadContext.contextualConsumer(expectedPriority -> {
Assert.assertEquals(Buffer.get().toString(), "overrideNamedThreadContextConfig-test-buffer-A",
"Context type (Buffer) that MicroProfile config specifies to be propagated was not propagated.");
Assert.assertEquals(Label.get(), "overrideNamedThreadContextConfig-test-label-A",
"Context type (Label) that MicroProfile config overrides to be propagated was not propagated.");
Assert.assertEquals(Integer.valueOf(Thread.currentThread().getPriority()), expectedPriority,
"Context type that MicroProfile config overrides to remain unchanged was changed.");
Thread.currentThread().setPriority(expectedPriority - 1);
});
Buffer.set(new StringBuffer("overrideNamedThreadContextConfig-test-buffer-B"));
Label.set("overrideNamedThreadContextConfig-test-label-B");
task.accept(newPriority);
Assert.assertEquals(Thread.currentThread().getPriority(), newPriority - 1,
"Context type that MicroProfile config overrides to remain unchanged was changed when task completed.");
}
finally {
// Restore original values
Buffer.set(null);
Label.set(null);
Thread.currentThread().setPriority(originalPriority);
}
}
/**
* Verify that MicroProfile config overrides the cleared, propagated, and unchanged attributes
* of a ThreadContext that is produced by the container when the application defines
* an unqualified parameter injection point that is annotated with ThreadContextConfig.
*/
@Test(dependsOnMethods = "beanInjected")
public void overrideContextPropagationForThreadContextParameterWithConfig() {
// Expected config is propagated=Label; unchanged=ThreadPriority, cleared=Remaining
Executor contextSnapshot = bean.getContextSnapshot();
Assert.assertNotNull(contextSnapshot,
"Unable to inject ThreadContext into method parameter. Cannot run test.");
int originalPriority = Thread.currentThread().getPriority();
try {
// Set non-default values
Buffer.set(new StringBuffer("overrideThreadContextConfig-test-buffer"));
Label.set("overrideThreadContextConfig-test-label");
int newPriority = originalPriority == 2 ? 1 : 2;
contextSnapshot.execute(() -> {
Assert.assertEquals(Buffer.get().toString(), "",
"Context type that MicroProfile config overrides to be cleared was not cleared.");
Assert.assertEquals(Label.get(), "setContextSnapshot-test-label",
"Context type that MicroProfile config overrides to be propagated was not correctly propagated from original snapshot.");
Assert.assertEquals(Thread.currentThread().getPriority(), originalPriority,
"Context type that MicroProfile config overrides to remain unchanged was changed.");
Thread.currentThread().setPriority(newPriority);
});
Assert.assertEquals(Thread.currentThread().getPriority(), newPriority,
"Context type that MicroProfile config overrides to remain unchanged was changed when task completed.");
}
finally {
// Restore original values
Buffer.set(null);
Label.set(null);
Thread.currentThread().setPriority(originalPriority);
}
}
/**
* Verify that 5 tasks/actions, and no more, can be queued when MicroProfile Config
* overrides the maxAsync value with 1 and leaves the maxAsync of 5 unmodified on a
* ManagedExecutor that is produced by the container when the application defines a
* parameter injection point that is annotated with ManagedExecutorConfig but not
* with any qualifiers.
*/
@Test(dependsOnMethods = "beanInjected")
public void overrideMaxAsyncWith1ForManagedExecutorParameter()
throws ExecutionException, InterruptedException, TimeoutException {
// Expected config is maxAsync=1; maxQueued=5; cleared=Transaction; propagated=Remaining
Assert.assertNotNull(producedExecutor, "Injection failure. Cannot run test.");
Phaser barrier = new Phaser(1);
try {
// First, use up the single maxAsync slot with a blocking task and wait for it to start
producedExecutor.submit(() -> barrier.awaitAdvanceInterruptibly(barrier.arrive() + 1));
barrier.awaitAdvanceInterruptibly(0, MAX_WAIT_NS, TimeUnit.NANOSECONDS);
// Use up queue positions
CompletableFuture<String> future1 = producedExecutor.supplyAsync(() -> "Q_1");
CompletableFuture<String> future2 = producedExecutor.supplyAsync(() -> "Q_2");
CompletableFuture<String> future3 = producedExecutor.supplyAsync(() -> "Q_3");
Future<String> future4 = producedExecutor.submit(() -> "Q_4");
Future<String> future5 = producedExecutor.submit(() -> "Q_5");
// Sixth attempt to queue a task must be rejected
try {
Future<String> future6 = producedExecutor.submit(() -> "Q_6");
Assert.fail("Exceeded maxQueued of 5. Future for 6th queued task/action is " + future6);
}
catch (RejectedExecutionException x) {
// test passes
}
// unblock and allow tasks to finish
barrier.arrive();
Assert.assertEquals(future1.get(MAX_WAIT_NS, TimeUnit.NANOSECONDS), "Q_1",
"Unexpected result of first task.");
Assert.assertEquals(future2.get(MAX_WAIT_NS, TimeUnit.NANOSECONDS), "Q_2",
"Unexpected result of second task.");
Assert.assertEquals(future3.get(MAX_WAIT_NS, TimeUnit.NANOSECONDS), "Q_3",
"Unexpected result of third task.");
Assert.assertEquals(future4.get(MAX_WAIT_NS, TimeUnit.NANOSECONDS), "Q_4",
"Unexpected result of fourth task.");
Assert.assertEquals(future5.get(MAX_WAIT_NS, TimeUnit.NANOSECONDS), "Q_5",
"Unexpected result of fifth task.");
}
finally {
barrier.forceTermination();
}
}
/**
* Verify that 2 tasks/actions, and no more, can be queued when MicroProfile Config
* overrides the maxQueued value with 2 on a ManagedExecutor that is produced by the
* container when the application defines a parameter injection point that is neither
* qualified nor annotated with ManagedExecutorConfig.
*/
@Test(dependsOnMethods = "beanInjected")
public void overrideMaxQueuedWith2ForManagedExecutorParameter()
throws ExecutionException, InterruptedException, TimeoutException {
// Expected config is maxAsync=1; maxQueued=2; propagated=Buffer,Label; cleared=Remaining
CompletableFuture<Integer> completedFuture = bean.getCompletedFuture();
Assert.assertNotNull(completedFuture, "Injection failure. Cannot run test.");
Phaser barrier = new Phaser(1);
try {
// First, use up the single maxAsync slot with a blocking task and wait for it to start
completedFuture.thenRunAsync(() -> {
try {
barrier.awaitAdvanceInterruptibly(barrier.arrive() + 1);
}
catch (InterruptedException x) {
throw new CompletionException(x);
}
});
barrier.awaitAdvanceInterruptibly(0, MAX_WAIT_NS, TimeUnit.NANOSECONDS);
// Use up queue positions
CompletableFuture<String> cf1 = completedFuture.thenApplyAsync(unused -> "first");
Assert.assertFalse(cf1.isDone(), "First action should be queued, not completed.");
CompletableFuture<String> cf2 = completedFuture.thenApplyAsync(unused -> "second");
Assert.assertFalse(cf2.isDone(), "Second action should be queued, not completed.");
// Third attempt to queue a task must be rejected
try {
CompletableFuture<String> cf3 = completedFuture.thenApplyAsync(unused -> "third");
// CompletionStage interface does not provide detail on precisely how to report rejection,
// so tolerate both possibilities: exception raised or stage returned with exceptional completion.
Assert.assertTrue(cf3.isDone() && cf3.isCompletedExceptionally(),
"Exceeded maxQueued of 2. Future for 3rd queued task/action is " + cf3);
}
catch (RejectedExecutionException x) {
// test passes
}
// unblock and allow tasks to finish
barrier.arrive();
Assert.assertEquals(cf1.get(MAX_WAIT_NS, TimeUnit.NANOSECONDS), "first",
"Unexpected result of first task.");
Assert.assertEquals(cf2.get(MAX_WAIT_NS, TimeUnit.NANOSECONDS), "second",
"Unexpected result of second task.");
}
finally {
barrier.forceTermination();
}
}
/**
* Verify that 3 tasks/actions, and no more, can be queued when MicroProfile Config
* overrides the maxQueued value with 3 on a ManagedExecutor that is produced by the
* container because the application annotated an unqualified injection point with
* the ManagedExecutorConfig annotation.
*/
@Test(dependsOnMethods = "beanInjected")
public void overrideMaxQueuedWith3ForManagedExecutorFieldWithConfig()
throws ExecutionException, InterruptedException, TimeoutException {
// Expected config is maxAsync=2; maxQueued=3; propagated=Label; cleared=Remaining
ManagedExecutor executor = bean.getExecutorWithConfig();
Assert.assertNotNull(executor,
"Unable to inject ManagedExecutor with ManagedExecutorConfig. Cannot run test.");
Phaser barrier = new Phaser(2);
try {
// First, use up both maxAsync slots with blocking tasks and wait for those tasks to start
CompletableFuture<Integer> blocker1 = executor.supplyAsync(() -> barrier.awaitAdvance(barrier.arriveAndAwaitAdvance()));
CompletableFuture<Integer> blocker2 = executor.supplyAsync(() -> barrier.awaitAdvance(barrier.arriveAndAwaitAdvance()));
barrier.awaitAdvanceInterruptibly(0, MAX_WAIT_NS, TimeUnit.NANOSECONDS);
// Use up queue positions
Future<String> future1 = executor.supplyAsync(() -> "q1");
Future<String> future2 = executor.supplyAsync(() -> "q2");
Future<String> future3 = executor.submit(() -> "q3");
// Fourth attempt to queue a task must be rejected
try {
Future<String> cf4 = executor.submit(() -> "q4");
Assert.fail("Exceeded maxQueued of 3. Future for 4th queued task/action is " + cf4);
}
catch (RejectedExecutionException x) {
// test passes
}
// unblock and allow tasks to finish
barrier.arrive();
barrier.arrive(); // there are 2 parties in each phase
Assert.assertEquals(blocker1.get(MAX_WAIT_NS, TimeUnit.NANOSECONDS), Integer.valueOf(2),
"Unexpected result of first blocker task.");
Assert.assertEquals(blocker2.get(MAX_WAIT_NS, TimeUnit.NANOSECONDS), Integer.valueOf(2),
"Unexpected result of second blocker task.");
Assert.assertEquals(future1.get(MAX_WAIT_NS, TimeUnit.NANOSECONDS), "q1",
"Unexpected result of first task from queue.");
Assert.assertEquals(future2.get(MAX_WAIT_NS, TimeUnit.NANOSECONDS), "q2",
"Unexpected result of second task from queue.");
Assert.assertEquals(future3.get(MAX_WAIT_NS, TimeUnit.NANOSECONDS), "q3",
"Unexpected result of third task from queue.");
}
finally {
barrier.forceTermination();
}
}
/**
* Verify that 4 tasks/actions, and no more, can be queued when MicroProfile Config
* overrides the maxQueued value with 4 on a ManagedExecutor that is produced by the
* container because the application annotated an injection point with ManagedExecutorConfig
* and the NamedInstance qualifier.
*/
@Test(dependsOnMethods = "beanInjected")
public void overrideMaxQueuedWith4ForManagedExecutorFieldWithConfigAndName()
throws ExecutionException, InterruptedException, TimeoutException {
// Expected config is maxAsync=1, maxQueued=4; cleared=ThreadPriority,Buffer,Transaction; propagated=Remaining
Assert.assertNotNull(namedExecutor,
"Unable to inject ManagedExecutor qualified by NamedInstance. Cannot run test.");
Phaser barrier = new Phaser(1);
try {
// First, use up the single maxAsync slot with a blocking task and wait for it to start
namedExecutor.submit(() -> barrier.awaitAdvanceInterruptibly(barrier.arrive() + 1));
barrier.awaitAdvanceInterruptibly(0, MAX_WAIT_NS, TimeUnit.NANOSECONDS);
// Use up queue positions
CompletableFuture<String> cf1 = namedExecutor.supplyAsync(() -> "Q1");
CompletableFuture<String> cf2 = namedExecutor.supplyAsync(() -> "Q2");
CompletableFuture<String> cf3 = namedExecutor.supplyAsync(() -> "Q3");
CompletableFuture<String> cf4 = namedExecutor.supplyAsync(() -> "Q4");
// Fifth attempt to queue a task must be rejected
try {
CompletableFuture<String> cf5 = namedExecutor.supplyAsync(() -> "Q5");
// CompletableFuture interface does not provide detail on precisely how to report rejection,
// so tolerate both possibilities: exception raised or stage returned with exceptional completion.
Assert.assertTrue(cf5.isDone() && cf5.isCompletedExceptionally(),
"Exceeded maxQueued of 4. Future for 5th queued task/action is " + cf5);
}
catch (RejectedExecutionException x) {
// test passes
}
// unblock and allow tasks to finish
barrier.arrive();
Assert.assertEquals(cf1.get(MAX_WAIT_NS, TimeUnit.NANOSECONDS), "Q1",
"Unexpected result of first task.");
Assert.assertEquals(cf2.get(MAX_WAIT_NS, TimeUnit.NANOSECONDS), "Q2",
"Unexpected result of second task.");
Assert.assertEquals(cf3.get(MAX_WAIT_NS, TimeUnit.NANOSECONDS), "Q3",
"Unexpected result of third task.");
Assert.assertEquals(cf4.get(MAX_WAIT_NS, TimeUnit.NANOSECONDS), "Q4",
"Unexpected result of fourth task.");
}
finally {
barrier.forceTermination();
}
}
}