🏷 Async Programming
4 patterns
Topic: Async Programming
All Java patterns related to Async Programming — java.evolved
Concurrency
CompletableFuture chaining
Old
Future<String> future =
executor.submit(this::fetchData);
String data = future.get(); // blocks
String result = transform(data);
Modern
CompletableFuture.supplyAsync(
this::fetchData
)
.thenApply(this::transform)
.thenAccept(IO::println);
hover to see modern →
JDK 8+
learn more →
Concurrency
Unsafe thread termination to cooperative cancellation
Old
Thread worker = new Thread(this::runTask);
worker.start();
// May stop the thread while shared state is inconsistent.
worker.stop();
Modern
Future<?> worker = executor.submit(this::runTask);
// Requests interruption; the task must cooperate.
worker.cancel(true);
hover to see modern →
JDK 5+
learn more →
I/O
WebSocket clients with java.net.http
Old
WebSocketClient client =
new WebSocketClient(serverUri) {
@Override
public void onMessage(String message) {
handle(message);
}
};
client.connect();
Modern
HttpClient.newHttpClient()
.newWebSocketBuilder()
.buildAsync(serverUri,
new WebSocket.Listener() {
@Override
public CompletionStage<?> onText(
WebSocket socket,
CharSequence data,
boolean last) {
handle(data.toString());
return WebSocket.Listener.super
.onText(socket, data, last);
}
});
hover to see modern →
JDK 11+
learn more →
Enterprise
Message-Driven Bean vs Reactive Messaging
Old
@MessageDriven(activationConfig = {
@ActivationConfigProperty(
propertyName = "destinationType",
propertyValue = "jakarta.jms.Queue"),
@ActivationConfigProperty(
propertyName = "destination",
propertyValue = "java:/jms/OrderQueue")
})
public class OrderMDB implements MessageListener {
@Override
public void onMessage(Message message) {
TextMessage txt = (TextMessage) message;
processOrder(txt.getText());
}
}
Modern
@ApplicationScoped
public class OrderProcessor {
@Incoming("orders")
public void process(Order order) {
// automatically deserialized from
// the "orders" channel
fulfillOrder(order);
}
}
hover to see modern →
JDK 11+
learn more →