What's the purpose of AsyncContext.start(…) in Servlet 3.0?

后端 未结 4 2060
[愿得一人]
[愿得一人] 2020-12-12 23:29

Servlet API says about \"AsyncContext.start\":

void start(java.lang.Runnable run)

Causes the container to dispatch a thread, possibly from

4条回答
  •  死守一世寂寞
    2020-12-13 00:05

    One reason this can be useful is when you want to release the incoming web thread, do some other work, and after done - get back to the web thread (might be another thread, but still from the web server pool) to complete the original operation and send response to the client.

    For example:

    1. ac = request.startAsync();
    2. forward("some data", "another system"); // async outbound HTTP request
    3. (at this point, incoming servlet thread is released to handle other requests)
    4. (in some other, non-servlet thread, upon "forward" response arrival)
       ac.start(new Runnable() { /* send response to the client */ });
    

    You could, of course, send response in the non-servlet thread, but this has one disadvantage - you use non-servlet thread to do servlet-typical operations, which means you're implicitly changing the balance between amount of thread power reserved for servlet work vs. other work.

    In other words - it gives you the ability to post Runnable into servlet thread pool. Obviously these are rare needs, but still - it gives some reasoning for AsyncContext.start() method.

提交回复
热议问题