0
# Asynchronous Strategies
1
2
Non-blocking execution patterns with both blocking and non-blocking asynchronous strategies for improved scalability and resource utilization.
3
4
## Capabilities
5
6
### Basic Asynchronous Execution
7
8
Standard asynchronous execution using CompletionStage for non-blocking operations.
9
10
```java { .api }
11
@Asynchronous
12
public CompletionStage<ReturnType> asyncMethod();
13
14
@Asynchronous
15
public CompletableFuture<ReturnType> asyncMethodWithFuture();
16
```
17
18
#### Usage Example
19
20
```java
21
@ApplicationScoped
22
public class AsyncService {
23
24
// Async HTTP call
25
@Asynchronous
26
@Timeout(10000)
27
public CompletionStage<ApiResponse> callExternalApiAsync(String endpoint) {
28
return CompletableFuture.supplyAsync(() -> {
29
return httpClient.get(endpoint);
30
});
31
}
32
33
// Async database operation
34
@Asynchronous
35
@Retry(maxRetries = 3)
36
public CompletableFuture<List<User>> findUsersAsync(UserQuery query) {
37
return CompletableFuture.supplyAsync(() -> {
38
return userRepository.find(query);
39
});
40
}
41
42
// Async file processing
43
@Asynchronous
44
@Bulkhead(value = 4, waitingTaskQueue = 10)
45
public CompletionStage<ProcessingResult> processFileAsync(File file) {
46
return CompletableFuture.supplyAsync(() -> {
47
return fileProcessor.process(file);
48
});
49
}
50
}
51
```
52
53
### Non-blocking Asynchronous Execution
54
55
SmallRye-specific non-blocking asynchronous execution using Mutiny reactive types.
56
57
```java { .api }
58
@AsynchronousNonBlocking
59
public Uni<ReturnType> nonBlockingAsyncMethod();
60
61
@AsynchronousNonBlocking
62
public Multi<ReturnType> nonBlockingStreamMethod();
63
```
64
65
#### Usage Example
66
67
```java
68
@ApplicationScoped
69
public class ReactiveService {
70
71
@Inject
72
MutinyHttpClient httpClient;
73
74
@Inject
75
ReactiveUserRepository userRepository;
76
77
// Non-blocking HTTP call
78
@AsynchronousNonBlocking
79
@Timeout(8000)
80
@Retry(maxRetries = 2)
81
public Uni<ApiResponse> callApiNonBlocking(String endpoint) {
82
return httpClient.get(endpoint)
83
.map(response -> ApiResponse.from(response));
84
}
85
86
// Non-blocking database query returning single result
87
@AsynchronousNonBlocking
88
@CircuitBreaker(requestVolumeThreshold = 10, failureRatio = 0.5)
89
public Uni<User> findUserNonBlocking(Long userId) {
90
return userRepository.findById(userId);
91
}
92
93
// Non-blocking stream processing
94
@AsynchronousNonBlocking
95
@Bulkhead(value = 6, waitingTaskQueue = 15)
96
public Multi<ProcessedItem> processItemsNonBlocking(List<Item> items) {
97
return Multi.createFrom().iterable(items)
98
.map(item -> processor.process(item));
99
}
100
}
101
```
102
103
### Async with Fault Tolerance Combinations
104
105
Combining asynchronous execution with comprehensive fault tolerance strategies.
106
107
```java { .api }
108
@Asynchronous
109
@Retry(maxRetries = 3, delay = 1000)
110
@CircuitBreaker(requestVolumeThreshold = 15, failureRatio = 0.4)
111
@Timeout(15000)
112
@Fallback(fallbackMethod = "asyncFallback")
113
public CompletionStage<ReturnType> resilientAsyncMethod();
114
```
115
116
#### Usage Example
117
118
```java
119
@ApplicationScoped
120
public class ResilientAsyncService {
121
122
// Comprehensive async resilience pattern
123
@Asynchronous
124
@Retry(maxRetries = 3, delay = 2000)
125
@CircuitBreaker(requestVolumeThreshold = 10, failureRatio = 0.3)
126
@Timeout(20000)
127
@Fallback(fallbackMethod = "processPaymentFallback")
128
@Bulkhead(value = 5, waitingTaskQueue = 12)
129
public CompletionStage<PaymentResult> processPaymentAsync(PaymentRequest request) {
130
return CompletableFuture.supplyAsync(() -> {
131
return paymentGateway.process(request);
132
});
133
}
134
135
public CompletionStage<PaymentResult> processPaymentFallback(PaymentRequest request) {
136
return CompletableFuture.completedFuture(
137
PaymentResult.queued(request.getTransactionId())
138
);
139
}
140
141
// Non-blocking with comprehensive fault tolerance
142
@AsynchronousNonBlocking
143
@Retry(maxRetries = 5)
144
@ExponentialBackoff(factor = 2, maxDelay = 30000)
145
@CircuitBreaker(requestVolumeThreshold = 20, failureRatio = 0.5)
146
@RateLimit(value = 100, window = 1, windowUnit = ChronoUnit.MINUTES)
147
public Uni<DataProcessingResult> processDataAsync(DataProcessingRequest request) {
148
return dataProcessor.processAsync(request)
149
.onFailure().retry().withBackOff(Duration.ofSeconds(1))
150
.onFailure().recoverWithItem(DataProcessingResult.failed());
151
}
152
}
153
```
154
155
### Async Context Propagation
156
157
Proper context propagation for security, transaction, and request context in async operations.
158
159
#### Usage Example
160
161
```java
162
@ApplicationScoped
163
public class ContextAwareAsyncService {
164
165
@Inject
166
SecurityContext securityContext;
167
168
@Inject
169
RequestContext requestContext;
170
171
// Async operation with security context propagation
172
@Asynchronous
173
@RolesAllowed("USER")
174
public CompletionStage<UserData> getUserDataAsync(Long userId) {
175
return CompletableFuture.supplyAsync(() -> {
176
// Security context is automatically propagated
177
return userService.getData(userId);
178
});
179
}
180
181
// Non-blocking with request context
182
@AsynchronousNonBlocking
183
@Transactional
184
public Uni<SaveResult> saveDataAsync(DataEntity data) {
185
// Transaction context is propagated to reactive chain
186
return Uni.createFrom().item(() -> {
187
return dataRepository.save(data);
188
});
189
}
190
191
// Complex async workflow with context
192
@Asynchronous
193
@Authenticated
194
public CompletionStage<WorkflowResult> executeWorkflowAsync(WorkflowRequest request) {
195
return CompletableFuture
196
.supplyAsync(() -> workflowEngine.validate(request))
197
.thenCompose(validationResult -> {
198
if (validationResult.isValid()) {
199
return workflowEngine.executeAsync(request);
200
} else {
201
return CompletableFuture.completedFuture(
202
WorkflowResult.invalid(validationResult.getErrors())
203
);
204
}
205
});
206
}
207
}
208
```
209
210
### Reactive Streams and Event Processing
211
212
Asynchronous event processing and reactive streams handling.
213
214
#### Usage Example
215
216
```java
217
@ApplicationScoped
218
public class EventProcessingService {
219
220
@Inject
221
EventBus eventBus;
222
223
// Event stream processing
224
@AsynchronousNonBlocking
225
@RateLimit(value = 1000, window = 1, windowUnit = ChronoUnit.SECONDS)
226
public Multi<ProcessedEvent> processEventStream(Multi<Event> eventStream) {
227
return eventStream
228
.map(event -> eventProcessor.process(event))
229
.filter(result -> result.isValid())
230
.onFailure().retry().withBackOff(Duration.ofMillis(100));
231
}
232
233
// Async event publishing
234
@Asynchronous
235
@Bulkhead(value = 8, waitingTaskQueue = 20)
236
public CompletionStage<PublishResult> publishEventAsync(DomainEvent event) {
237
return CompletableFuture.supplyAsync(() -> {
238
return eventBus.publish(event);
239
});
240
}
241
242
// Message processing with backpressure
243
@AsynchronousNonBlocking
244
@Retry(maxRetries = 3)
245
public Uni<MessageProcessingResult> processMessageAsync(Message message) {
246
return messageProcessor.processAsync(message)
247
.onFailure(MessageFormatException.class).recoverWithNull()
248
.onFailure().retry().withBackOff(Duration.ofSeconds(1));
249
}
250
}
251
```
252
253
## Types
254
255
### Asynchronous Core Types
256
257
```java { .api }
258
// Java standard async types
259
interface CompletionStage<T> {
260
CompletionStage<T> thenApply(Function<T, U> fn);
261
CompletionStage<T> thenCompose(Function<T, CompletionStage<U>> fn);
262
CompletionStage<T> thenCombine(CompletionStage<U> other, BiFunction<T, U, V> fn);
263
CompletionStage<T> handle(BiFunction<T, Throwable, U> fn);
264
CompletionStage<T> exceptionally(Function<Throwable, T> fn);
265
}
266
267
interface CompletableFuture<T> extends CompletionStage<T> {
268
static <U> CompletableFuture<U> completedFuture(U value);
269
static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier);
270
static CompletableFuture<Void> runAsync(Runnable runnable);
271
}
272
```
273
274
### Mutiny Reactive Types
275
276
```java { .api }
277
// Mutiny Uni for single async values
278
interface Uni<T> {
279
Uni<T> map(Function<T, U> mapper);
280
Uni<T> flatMap(Function<T, Uni<U>> mapper);
281
Uni<T> onFailure();
282
Uni<T> onItem();
283
CompletionStage<T> subscribeAsCompletionStage();
284
}
285
286
// Mutiny Multi for streams
287
interface Multi<T> {
288
Multi<T> map(Function<T, U> mapper);
289
Multi<T> filter(Predicate<T> predicate);
290
Multi<T> onFailure();
291
Multi<T> onItem();
292
Uni<List<T>> collect().asList();
293
}
294
```
295
296
### Context Types
297
298
```java { .api }
299
// Security context for async operations
300
interface SecurityContext {
301
Principal getUserPrincipal();
302
boolean isUserInRole(String role);
303
}
304
305
// Request context propagation
306
interface RequestContext {
307
String getRequestId();
308
Map<String, Object> getAttributes();
309
}
310
```