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 threading model for Tomcat to process requests

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

Editor to share with you what the threading model of Tomcat processing requests is, I believe most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's go to know it!

I. Preface

The JAVA backend project runs in the container tomcat. Due to the built-in tomcat container of springboot, its default configuration shields a lot of knowledge of tomcat, but the learning and understanding of tomcat is more important, so special reference materials deepen understanding. This article mainly discusses the request process of tomcat9 under springboot integration, and the thread model is NIO.

II. Tomcat structure

Find a structure diagram, the meaning and function of each module will not be explained in detail, you can search other articles

Third, discuss how tomcat handles requests

I drew a structure of connector myself.

1. Initialize

After springboot starts, org.springframework.context.support.AbstractApplicationContext#finishRefresh, go in here and call the org.springframework.boot.web.servlet.context.WebServerStartStopLifecycle.start () method to start TomcatWebServer and initialize tomcat.

Through such a call chain to org.apache.tomcat.util.net.NioEndpoint#startInternal (), initialize Acceptor and Poller in Endpoint, both of which implement the Runnable interface, and then start through the thread start.

2. How to handle client requests

Acceptor: a receiver that accepts scoket network requests and calls setSocketOptions () to encapsulate it into a NioSocketWrapper and register it in Poller's events. Notice to check the run method org.apache.tomcat.util.net.Acceptor#run

@ Override public void run () {int errorDelay = 0; try {/ / Loop until we receive a shutdown command while (! stopCalled) {/ / Loop if endpoint is paused while (endpoint.isPaused () & &! stopCalled) {state = AcceptorState.PAUSED Try {Thread.sleep (50);} catch (InterruptedException e) {/ / Ignore}} if (stopCalled) {break } state = AcceptorState.RUNNING; try {/ / if we have reached max connections, wait endpoint.countUpOrAwaitConnection () / / Endpoint might have been paused while waiting for latch / / If that is the case, don't accept new connections if (endpoint.isPaused ()) {continue;} U socket = null Try {/ / wait for the next request to come in socket = endpoint.serverSocketAccept ();} catch (Exception ioe) {/ / We didn't get a socket endpoint.countDownConnection () If (endpoint.isRunning ()) {/ / Introduce delay if necessary errorDelay = handleExceptionWithDelay (errorDelay); / / re-throw throw ioe;} else {break }} / / Successful accept, reset the error delay errorDelay = 0 / / Configure the socket if (! stopCalled & &! endpoint.isPaused ()) {/ / register socket to Poller and generate PollerEvent event if (! endpoint.setSocketOptions (socket)) {endpoint.closeSocket (socket) } else {endpoint.destroySocket (socket);}} catch (Throwable t) {ExceptionUtils.handleThrowable (t); String msg = sm.getString ("endpoint.accept.fail"); / / APR specific. / / Could push this down but not sure it is worth the trouble. If (t instanceof Error) {Error e = (Error) t If (e.getError ()) {/ / Not an error on HP-UX so log as a warning / / so it can be filtered out on that platform / / See bug 50273 log.warn (msg, t) } else {log.error (msg, t);}} else {log.error (msg, t) } finally {stopLatch.countDown ();} state = AcceptorState.ENDED;}

Poller: polling for whether there are any events arriving. After a request event arrives, the query Selector fetches all requests in the way of NIO, traverses the requirements of each request, and assigns it to the executor thread pool for execution. View org.apache.tomcat.util.net.NioEndpoint.Poller#run ()

Public void run () {/ / Loop until destroy () is called while (true) {boolean hasEvents = false; try {if (! close) {hasEvents = events () If (wakeupCounter.getAndSet (- 1) > 0) {/ If we are here, means we have other stuff to do / / Do a non blocking select keyCount = selector.selectNow () } else {keyCount = selector.select (selectorTimeout);} wakeupCounter.set (0);} if (close) {events (); timeout (0, false) Try {selector.close ();} catch (IOException ioe) {log.error (sm.getString ("endpoint.nio.selectorCloseFail"), ioe);} break } / / Either we timed out or we woke up, process events first if (keyCount = = 0) {hasEvents = (hasEvents | events ());}} catch (Throwable x) {ExceptionUtils.handleThrowable (x) Log.error (sm.getString ("endpoint.nio.selectorLoopError"), x); continue;} / / query selector to fetch all requests Iterator iterator = keyCount > 0? Selector.selectedKeys (). Iterator (): null; / / Walk through the collection of ready keys and dispatch / / any active event While (iterator! = null & & iterator.hasNext ()) {SelectionKey sk = iterator.next (); iterator.remove (); NioSocketWrapper socketWrapper = (NioSocketWrapper) sk.attachment (); / / processing request key if (socketWrapper! = null) {processKey (sk, socketWrapper) }} / / Process timeouts timeout (keyCount,hasEvents);} getStopLatch (). CountDown ();}

The request process is roughly as shown below:

These are all the contents of the article "what is the threading model for Tomcat processing requests?" Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

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

Development

Wechat

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

12
Report