CompletionStage support in server-side JAX-RS

JAX-RS 2.1 (part of Java EE 8) now supports returning a CompletionStage to mark the request as eligible for asynchronous processing. This is in addition to the AsyncResponse API which has been available since JAX-RS 2.0 (Java EE 7)

Even the Client API has added support for reactive-style programming by providing support for CompletionStage API, but this blog will focus on the server-side support

The advantage this approach has over the AsyncResponse based API is that it is richer and allows you to create asynchronous pipelines. Let’s look at an example – available on Github. It is simple and slightly contrived, but hopefully it should help get the point across 🙂

  • It starts with a HTTP GET to /booking/cabs/<user> which invokes the getCab method
    • the method returns a CompletionStage and returns immediately
    • the thread which served the request is now freed up
  • and then its about creating the asynchronous pipeline
    • we orchestrate the tasks for user validation and driver search using thenComposeAsync – this gives a CompletableFuture i.e. the searchDriverTask
    • we then supply a Function which takes the driver (returned by the above step) and invokes the notifyUser method – this is the CompletionStage which we actually return i.e. notifyUserTask – this is obviously executed later on, all we did was compose the sequence
  • once the process is completed (delays are introduced using Thread.sleep() ), the response is sent back to the user – internally, our CompletableFuture completes

To run using Docker


Further reading

About Abhishek

Loves Go, NoSQL DBs and messaging systems
This entry was posted in Docker, Java, Java EE and tagged , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s