0
votes

Here's a sample code from Jersey docs for Asynchronous Services:

@Path("/resource")
public class AsyncResource {
    @GET
    public void asyncGet(@Suspended final AsyncResponse asyncResponse) {

        new Thread(new Runnable() {
            @Override
            public void run() {
                String result = veryExpensiveOperation();
                asyncResponse.resume(result);
            }

            private String veryExpensiveOperation() {
                // ... very expensive operation
            }
        }).start();
    }
}

Considering that container is already in charge of releasing the connection handling thread back to the pool and handing the request processing to a worker thread, I'm wondering why we still need to spawn a new thread programmatically? Shouldn't this be just a matter of container configuration (setting number of worker threads)?

2

2 Answers

1
votes

There is no need to spwan a new thread like this. If you are in an JavaEE environment you can simply place an @Asynchronous annotation to your method:

@GET
@Asynchronous
public void asyncGet(@Suspended final AsyncResponse asyncResponse) {
        String result = veryExpensiveOperation();
        asyncResponse.resume(result);
}

I you need extended thread pooling you can also have a look at ManagedExecutorService.

0
votes

Shouldn't this be just a matter of container configuration (setting number of worker threads)?

Actually you can configure the number of container worker threads, but you are still bound by them. If you have 10 container threads then you can process 10 requests at the same time. If you have 100 threads, then you can have 100 simultaneous requests

Async web requests on the other hand decouple the request/response objects (and jax-rs uses servlets underneath in case of servlet-container deployment) from the worker thread. Thus you can have 10 threads, but 1000 requests for instance (keep reading).

I'm wondering why we still need to spawn a new thread programmatically?

It's meaningless to decouple the request from the thread if you are still going to process it in the same thread, because in that case there is absolutely no difference between async/sync requests.

Also you don need to spawn a new thread. Actually that's a horrible solution. Thread creation is expensive. Instead you should submit the runnables to a thread pool.

So what good are async requests then ? They are good for operations that take a lot of time to complete. Do the following experiment.

  1. Configure tomcat (or your server of choice) to use a pool of 10 threads.
  2. Make your resource to just sleep for 10 seconds.
  3. Request it as many times as you can.
  4. Make your resource asynchronous and instead of waiting in it, submit the runnables which just wait for 10seconds to a thread pool -> how many requests can you make now ?