Skip to content

Commit bd1b09e

Browse files
committed
2 parents 4f4a8b6 + e309da6 commit bd1b09e

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

README.md

+31
Original file line numberDiff line numberDiff line change
@@ -117,6 +117,37 @@ public @async CompletionStage<String> bar(int i) {
117117
return async(result);
118118
}
119119
```
120+
It's worth to mention, that when developing code with async/await you should avoid so-called ["async/await hell"](https://medium.com/@7genblogger/escaping-so-called-async-await-hell-in-node-js-b5f5ba5fa9ca). In short, pay special attention what parts of your code may be executed in parallel and what parts require serial execution. Consider the following example:
121+
```java
122+
public @async CompletionStage<Long> calculateTotalPrice(Order order) {
123+
Long rawItemsPrice = await( calculateRawItemsPrice(order) );
124+
Long shippingCost = await( calculateShippingCost(order) );
125+
Long taxes = await( calculateTaxes(order) );
126+
return async(rawItemsPrice + shippingCost + taxes);
127+
}
128+
129+
protected @async CompletionStage<Long> calculateRawItemsPrice(Order order) {
130+
...
131+
}
132+
133+
protected @async CompletionStage<Long> calculateShippingCost(Order order) {
134+
...
135+
}
136+
137+
protected @async CompletionStage<Long> calculateTaxes(Order order) {
138+
...
139+
}
140+
```
141+
In the above example all async methods `calculateRawItemsPrice`, `calculateShippingCost`, `calculateTaxes` are executed serially, one by one, hence the performance is degraded comparing to the following parallelized solution:
142+
```java
143+
public @async CompletionStage<Long> calculateTotalPrice(Order order) {
144+
CompletionStage<Long> rawItemsPrice = calculateRawItemsPrice(order);
145+
CompletionStage<Long> shippingCost = calculateShippingCost(order);
146+
CompletionStage<Long> taxes = calculateTaxes(order);
147+
return async( await(rawItemsPrice) + await(shippingCost) + await(taxes) );
148+
}
149+
```
150+
This way all inner async operations are started (almost) simualtenously and are running in parallel, unlike in the first example.
120151

121152
# Generators
122153

0 commit comments

Comments
 (0)