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();
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值