【发布时间】:2016-12-21 13:12:29
【问题描述】:
从下面的源码看来,如果同时有两个请求,那么第一个请求调用socket = serverSocket.accept(),处理完第一个请求后,再处理第二个请求通过调用serverSocket.accept(),所以似乎tomcat在await()方法中一一处理请求,而不是每个线程一个请求同时处理它们,但是从下面的文档中,它指出“他 ThreadPoolExecutor 分配了一个 TaskThread 来处理请求。” ,但是我没有看到 ThreadPoolExecutor 如何分配一个 TaskThread 来处理请求。任何人都可以给出一些提示,从源代码的角度来看,tomcat 如何将每个请求分配给一个线程? https://github.com/apache/tomcat/blob/83b3ea892aa03b4a8bbfdfe2b9a2e28755cb52cc/webapps/docs/architecture/startup/serverStartup.txt
try {
awaitThread = Thread.currentThread();
// Loop waiting for a connection and a valid command
while (!stopAwait) {
ServerSocket serverSocket = awaitSocket;
if (serverSocket == null) {
break;
}
// Wait for the next connection
Socket socket = null;
StringBuilder command = new StringBuilder();
try {
InputStream stream;
long acceptStartTime = System.currentTimeMillis();
try {
**socket = serverSocket.accept();**
socket.setSoTimeout(10 * 1000); // Ten seconds
stream = socket.getInputStream();
} catch (SocketTimeoutException ste) {
// This should never happen but bug 56684 suggests that
// it does.
log.warn(sm.getString("standardServer.accept.timeout",
Long.valueOf(System.currentTimeMillis() - acceptStartTime)), ste);
continue;
} catch (AccessControlException ace) {
log.warn("StandardServer.accept security exception: "
+ ace.getMessage(), ace);
continue;
} catch (IOException e) {
if (stopAwait) {
// Wait was aborted with socket.close()
break;
}
log.error("StandardServer.await: accept: ", e);
break;
}
// Read a set of characters from the socket
int expected = 1024; // Cut off to avoid DoS attack
while (expected < shutdown.length()) {
if (random == null)
random = new Random();
expected += (random.nextInt() % 1024);
}
while (expected > 0) {
int ch = -1;
try {
ch = stream.read();
} catch (IOException e) {
log.warn("StandardServer.await: read: ", e);
ch = -1;
}
// Control character or EOF (-1) terminates loop
if (ch < 32 || ch == 127) {
break;
}
command.append((char) ch);
expected--;
}
} finally {
// Close the socket now that we are done with it
try {
if (socket != null) {
socket.close();
}
} catch (IOException e) {
// Ignore
}
}
【问题讨论】:
标签: tomcat