Cogman
Cogman

Reputation: 2150

Why wouldn't you use Async responses for all resources in JAX-RS?

I'm combing over the JAX-RS spec. Everything seems simple enough. But I'm left with the question. Why wouldn't I do this everywhere? In otherwords, what are the downsides? Since most resource requests end up hitting the DB, wouldn't you want all of them to be Async?

What are the downsides that I should be aware of? Is there a bunch of extra overhead? I haven't been able to find anything that says why you shouldn't do this, just how to do this.

Upvotes: 3

Views: 338

Answers (1)

Vikas Sachdeva
Vikas Sachdeva

Reputation: 5803

I think it is not about Async feature of JAX-RS, it is about synchronous vs asynchronous operations.

As you know synchronous operations use single thread to execute the task where as asynchronous operations require creation of additional thread to execute the task. Now, this is the overhead - creation of a new thread, executing task in new thread and then destroying that thread. This overhead results in performance.

Although, you can reuse already created threads instead of always creating new thread. But, still additional thread exists which impacts performance.

For example, a synchronous web service which processes around 1000 parallel requests. So, for handling these requests, 1000 threads will get created. Now, consider the same situation in asynchronous environment. For handling 1000 parallel requests, 2000 threads will get created - 1000 for handling requests and 1000 for asynchronous operation processing.

Now, you can understand the load on the operating system. High load will impact the performance. If the task is expensive i.e. takes time to execute, overall turn around time will decrease compare to synchronous execution. However, if the task is not expensive like db operations. overall turn around time will increase compare to synchronous execution. This is due to overhead of handling additional threads.

Another reason is complexity, asynchronous is always complex, requires additional code for making things asynchronous. However, framework like Jersey hides this complexity up to some extent.

So, it is always recommended to process expensive operations i.e the operations whose execution will take time, in asynchronous way so that overall turn around time can be decreased. Asynchronous execution for each operation is not recommended.

Upvotes: 2

Related Questions