Asynchronous programming with Java

1 minute

We are all aware of the rise of  asynchronous and reactive programing paradigms. Java has already started catching up with other newer languages like Java Script, Go, Python,… that supports this natively. Starting with Java 9 there is  possibility support for Reactive Streams. Unfortunately the shift with Java is always slower than expected.

On the quest to optimize my Java code and to start writing reactive/async code I started looking in to the Eclipse Vert.x. This is an opensource extension for Java that delivers async mechanisms as well as providing bunch of other tools needed for running the whole asynchronous ecosystem as well as focusing on microservice/cloud  paradigm. On top of that there is a native support for JavaRx APIs that many of you are already familiar with.

The sentence that stuck in my head:

If you have 3 request, the sync model guaranties to deliver the first response faster than the async model but on the other hand async guaranties to deliver response to all 3 in total faster.

Unlike in synchronous programing where requests are processed/handled one by one in order asynchronous model receives a request, generates a call back for it, starts processing it but is free to receive another request. So when another request comes it again generates the callback and so on… When the task is done the callback is called the result of request can be sent. I am referring to request as an action/process/operation,… This saves a lot of time that is wasted on waiting for the request to complete in synchronous programming.

To demonstrate this I have created a simple example where I compare the execution of 5 HTTP GET requests to famous websites.

In the first example I will be using standard java synchronous model. To ease the syntax I am using OkHttp Client which proved itself as very fast and easy HTTP client for Java.

As stated above for async example I will be using Eclipse Vertx. The syntax is a little strange if you haven’t been programing with reactive streams, Futures, Java Rx but for this example there is nothing fancy or hard.

After running both of these examples multiples times and timing all of the runs here are the numbers:

Run #idSyncExampleAsyncExample
Run 13896 ms1638 ms
Run 23846 ms1750 ms
Run 3
4352 ms1774 ms
Average4031.33 ms1720.66 ms


I hope these numbers and the pure idea behind async programing have inspired you to dig deeper in to this paradigm. There are a lot of tools and services which provide these capabilities. 

For the end I will leave you with some documentation and tutorials you can follow up. Enjoy!!!

Post A Reply