Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the implementation principle of asynchronous Servlet in Tomcat?

2025-03-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

What is the implementation principle of asynchronous Servlet in Tomcat? I believe many inexperienced people don't know what to do about it. Therefore, this paper summarizes the causes and solutions of the problem. Through this article, I hope you can solve this problem.

First of all, let's start with the use of asynchronous Servlet.

Our steps are roughly as follows:

Declare Servlet, pay attention to adding the attribute of asyncSupported, and enable asynchronous processing support. @ WebServlet (urlPatterns = "/ demo", asyncSupported = true)

Within Servlet, where independent threading is needed, use request to get the asynchronous Context. AsyncContext ctx = req.startAsync ()

In a separate thread, using asynchronous Context, you can get its bound request and response, and at this point, you can continue to write logic in the same way as the original Servlet.

After the operation within a separate thread is finished, you need to call the complet method of the asynchronous Context to end the asynchronous thread.

It should be noted that the asynchronous Servlet has a corresponding timeout. If the operation is not completed within the specified time, the response will still follow the end logic of the original Servlet. Subsequent asynchronous operations may encounter exceptions when they finish executing and writing back.

The above are the main steps for using asynchronous Servlet, so how is it implemented behind this? Let's take a look at the principle.

We are getting asynchronous Context through Request. What happens behind this step?

Public AsyncContext startAsync () {

Return startAsync (getRequest (), response.getResponse ())

}

Public AsyncContext startAsync (ServletRequest request

ServletResponse response) {

If (! isAsyncSupported ()) {/ / Note 1

Throw new IllegalStateException (sm.getString ("request.asyncNotSupported"))

}

If (asyncContext = = null) {

AsyncContext = new AsyncContextImpl (this)

}

AsyncContext.setStarted (getContext (), request, response

Request==getRequest () & & response==getResponse () .getResponse ()

AsyncContext.setTimeout (getConnector (). GetAsyncTimeout ()); / / Note 2

Return asyncContext

}

Note 1 above, as mentioned in the previous step, when configuring annotations, you should enable asynchronous processing support, otherwise an exception will be thrown directly at this step.

Note 2, which is the asynchronous timeout setting mentioned earlier.

We see that the whole method generates a corresponding AsyncContext through the current request and response, and configures it accordingly.

In the setStart method, the main logic executed is as follows:

Public void setStarted (Context context, ServletRequest request

ServletResponse response, boolean originalRequestResponse) {

This.request.getCoyoteRequest (). Action

ActionCode.ASYNC_START, this); / / Note 3

List listenersCopy = new ArrayList ()

ListenersCopy.addAll (listeners)

Listeners.clear ()

For (AsyncListenerWrapper listener: listenersCopy) {

Try {

Listener.fireOnStartAsync (event); / / Note 4

} catch (Throwable t) {

}

}

}

As noted in note 3 above, within Tomcat, many response status notifications are returned in ActionCode in a similar way, including the method calls to complete mentioned earlier.

Note 4, which is about asynchronous Context, you can add a lot of asynchronous Listener to notify Listener when a specific event occurs.

In the Servlet specification, the startAsync method is described as follows:

A call to this method ensures that the response isn't committed when the application exits out of the service method. It is committed when AsyncContext.complete is called on the returned AsyncContext or the AsyncContext times out and there are no listeners associated to handle the time out. The timer for async time outs will not start until the request and it's associated response have returned from the container. The AsyncContext could be used to write to the response from the async thread. It can also be used to just notify that the response is not closed and committed.

The above explanation can help us understand the implementation principle of part of the asynchronous Servlet, and we sort out the specific logic from the source code.

As we analyzed in the previous article, the processing of the entire request, to the invocation of the components within the Container, is from EndPoint to CoyoteAdaptor. Where, in the code of Endpoint, the call starts on this line:

GetAdapter () .service (request response)

After that, when the entire service execution is completed, the Adaptor will judge according to the request type. For non-asynchronous and comet requests, request and response finished operations will be performed, and recycle operations will be performed at the same time.

AsyncContextImpl asyncConImpl = (AsyncContextImpl) request.getAsyncContext ()

If (asyncConImpl! = null) {

Async = true

} else if (! comet) {

Request.finishRequest ()

Response.finishResponse ();}

Note that in finishResponse, outputBuffer.close (); is executed, and in recycle, restrictions are also made based on the type of request. Note that in CoyoteAdaptor, the specific type of request is determined, whether it is comet or async.

If (! comet & &! async | | error.get ()) {

Request.recycle ()

Response.recycle ()

At this point, the OutputBuffer will be reset, so for a normal Servlet, other operations cannot be written back.

In addition, Processor determines the type of request to decide whether to perform a specific operation, such as

If (! isAsync () & &! comet) {

EndRequest ()

}

We see that the endRequest operation is performed when the request is not asynchronous and it is not a comet request. When the Socket status is returned, the judgment is also made according to the request type. For asynchronous requests, the Socket status returned is LONG.

Else if (isAsync () | | comet) {

Return SocketState.LONG

In the Protocol class, when the type is judged to be LONG, the following actions are performed:

If (state = = SocketState.LONG) {

/ / In the middle of processing a request/response. Keep the

/ / socket associated with the processor. Exact requirements

/ / depend on type of long poll

Connections.put (socket, processor)

LongPoll (wrapper, processor); / / configure the properties of processor

Thus the request can be processed using the original processor.

As for the complete operation after the completion of asynchronous Context execution, it mainly returns an ActionCode of complete, determines that the request execution is completed in Processor, sets SocketStatus to OPEN_READ, and starts the next round of request reception.

Public void complete () {

Check ()

Request.getCoyoteRequest () .action (ActionCode.ASYNC_COMPLETE null)

}

Case ASYNC_COMPLETE: {

SocketWrapper.clearDispatches ()

If (asyncStateMachine.asyncComplete ()) {

Endpoint.processSocket (this.socketWrapper, SocketStatus.OPEN_READ, true)

}

Break

}

The above is the basic implementation principle of asynchronous Servlet. To sum up, the main points are:

LongPool of Socket after the main line request has been executed

The status of response is not set to finished, and OutputBuffer can still be written back if it is not close.

After reading the above, have you mastered the principle of implementing asynchronous Servlet in Tomcat? If you want to learn more skills or want to know more about it, you are welcome to follow the industry information channel, thank you for reading!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report