Did You Know? Asynchronous REST Requests and Responds with Java EE and MicroProfile

Java EE 8 fully supports asynchronous handling of REST requests and responses, on both client and server side. This is useful to optimize throughput of an application or even when adopting reactive principles. MicroProfile type-safe REST client API also supports this concept to allow you to call REST services asynchronously with a much more straightforward way with plain Java interfaces.

With the JAX-RS API in Java EE 8, you can create a method in your rest resource class that returns a CompletionStage like this:

The above code returns a completed future, which isn't very helpful though. In real application, you would either return a non-completed future and complete it asynchronously later, or return a future retrieved from another asynchronous method call. In such case, the application would wait until the future is completed asynchronously in another thread before sending a response back. But meanwhile, the current thread would be released and free for processing another request.

On the client side, the JAX-RS API provides methods that call REST resources asynchronously and return CompletionStage. This allows adding handlers that will be executed asynchronously when the response is ready and the code still stays readable. The current thread is again free to work in parallel to the asynchronous call or to be released to process other tasks. You can access the asynchronous client methods with calling the rx() method on the client object:

About Payara

Payara Server - Derived from GlassFish, with 24/7 Production Support. Payara Server is a drop in replacement for GlassFish Server Open Source Edition, with the peace of mind of quarterly releases containing enhancements, bug fixes and patches.