Tomcat的接收线程们

在connector部分,有个类叫AprEndpoint,在org.apache.tomcat.util.net中。该类有如下功能:
1. 获得客户端的socket
2. 将获得的socket交给该类线程池(是由一个栈实现的)中的闲置线程
3. 各线程调用AprEndpoint中的handler变量对socket进行处理(process()函数)

注:handler是AjpConnectionHandler或者Http11ConnectionHandler的实例。

看这个之前,我是有几个问题不太确定,所以看了一下源代码,什么问题呢?
tomcat的socket是非阻塞式工作吗?
多线程处理请求到底是在哪个环节开始的呢?

看了之后,发现,tomcat的socket居然是阻塞式的

long socket = Socket.accept(serverSock);

// 从线程池中取出闲置线程来处理收到的socket
getWorkerThread().assign(socket, true);


该线程类叫Worker,用了assign和await两个函数来实现生产者和消费者模型,个人觉得有点多余。通过getWorkerThread()拿到的一定是闲置线程,还搞什么同步呢?

protected class Worker implements Runnable {
protected Thread thread = null;
protected boolean available = false;
protected long socket = 0;
protected boolean options = false;

protected synchronized void assign(long socket, boolean options) {
// Wait for the Processor to get the previous Socket
while (available) {
try {
wait();
} catch (InterruptedException e) {
}
}

// Store the newly available Socket and notify our thread
this.socket = socket;
this.options = options;
available = true;
notifyAll();
}
/**
* Await a newly assigned Socket from our Connector, or <code>null</code>
* if we are supposed to shut down.
*/
protected synchronized long await() {

// Wait for the Connector to provide a new Socket
while (!available) {
try {
wait();
} catch (InterruptedException e) {
}
}
// Notify the Connector that we have received this Socket
long socket = this.socket;
available = false;
notifyAll();
return (socket);
}
/**
* The background thread that listens for incoming TCP/IP connections and
* hands them off to an appropriate processor.
*/
public void run() {

// Process requests until we receive a shutdown signal
while (running) {

// Wait for the next socket to be assigned
long socket = await();
if (socket == 0)
continue;

// Process the request from this socket
if ((options && !setSocketOptions(socket)) || !handler.process(socket)) {
// Close socket and pool
Socket.destroy(socket);
socket = 0;
}
// Finish up this request
recycleWorkerThread(this);
}
}
/**
* Start the background processing thread.
*/
public void start() {
thread = new ThreadWithAttributes(AprEndpoint.this, this);
thread.setName(getName() + "-" + (++curThreads));
thread.setDaemon(true);
thread.start();
}
}

版权声明:本文为iteye_5077原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。