Tomcat 源码学习之JIoEndpoint
来源:互联网 发布:淘宝电子产品拆封退货 编辑:程序博客网 时间:2024/06/03 17:46
本来想自己写的,结果在网上找到别人写的,概括的非常详细,就直接转过来了:
Tomcat中提供了多种处理Socket的实现:JIoEndpoint、AprEndpoint和NioEndpoint。其中JIoEndpoint是最常见的一种实现方式。
JIOEndpoint中的线程有3部分:Socket侦听线程、监控线程和Executor。
Socket侦听线程
该线程由内部类Acceptor实现其Runnable接口,使用JDK的ServerSocket类监听某个端口,当socket连接进来时,构建一个task,交给Executor来处理。
监控线程
该线程由AsyncTimeout实现其Runnable接口,不断遍历Request队列,为Timeout的Request构造一个TIMEOUT task,交给Executor来处理。
Executor
Executor 负责提供工作线程用来处理侦听线程和监控线程构造的task。该task会完成对Request回应。如果用户没有指定 Executor,JIoEndpoint中会自动创建 org.apache.tomcat.util.threads.ThreadPoolExecutor作为默认实现。
按照工作流程的顺序介绍一下各个部分:
初始化:bind()
public void bind() throws Exception {
if (acceptorThreadCount == 0) {
acceptorThreadCount = 1;
}
if (serverSocketFactory == null) {
if (isSSLEnabled()) {
ServerSocketFactory = handler.getSslImplementation().getServerSocketFactory(this);
} else {
ServerSocketFactory = new DefaultServerSocketFactory(this);
}
}
try {
if (getAddress() == null) {
serverSocket = serverSocketFactory.createSocket(getPort(),
getBacklog());
} else {
serverSocket = serverSocketFactory.createSocket(getPort(),
getBacklog(), getAddress());
}
} catch (BindException orig) {
String msg;
if (getAddress() == null)
msg = orig.getMessage() + ” <null>:” + getPort();
else
msg = orig.getMessage() + ” ” +
getAddress().toString() + “:” + getPort();
BindException be = new BindException(msg);
be.initCause(orig);
throw be;
}
}
}
public void startInternal() throws Exception {
running = true;
paused = false;
if (getExecutor() == null) {
createExecutor();
}
initializeConnectionLatch();
for (int i = 0; i < acceptorThreadCount; i++) {
Thread acceptorThread = new Thread(new Acceptor(),
getName() + “-Acceptor-” + i);
acceptorThread.setPriority(threadPriority);
acceptorThread.setDaemon(getDaemon());
acceptorThread.start();
}
// Start async timeout thread
Thread timeoutThread = new Thread(new AsyncTimeout(),
getName() + “-AsyncTimeout”);
timeoutThread.setPriority(threadPriority);
timeoutThread.setDaemon(true);
timeoutThread.start();
}
}
@Override
public void run() {
while (running) {
while (paused && running) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// Ignore
}
}
break;
}
try {
//if we have reached max connections, wait
awaitConnection();
try {
// Accept the next incoming connection from the server
// socket
socket = serverSocketFactory.acceptSocket(serverSocket);
} catch (IOException ioe) {
// Introduce delay if necessary
errorDelay = handleExceptionWithDelay(errorDelay);
// re-throw
throw ioe;
}
// Successful accept, reset the error delay
errorDelay = 0;
if (setSocketOptions(socket)) {
// Hand this socket off to an appropriate processor
if (!processSocket(socket)) {
// Close socket right away
try {
socket.close();
} catch (IOException e) {
// Ignore
}
} else {
countUpConnection();
}
} else {
// Close socket right away
try {
socket.close();
} catch (IOException e) {
// Ignore
}
}
} catch (IOException x) {
if (running) {
log.error(sm.getString(“endpoint.accept.fail”), x);
}
} catch (NullPointerException npe) {
if (running) {
log.error(sm.getString(“endpoint.accept.fail”), npe);
}
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
log.error(sm.getString(“endpoint.accept.fail”), t);
}
// The processor will recycle itself when it finishes
}
}
}
protected boolean processSocket(Socket socket) {
// Process the request from this socket
try {
SocketWrapper<Socket> wrapper = new SocketWrapper<Socket>(socket);
wrapper.setKeepAliveLeft(getMaxKeepAliveRequests());
// During shutdown, executor may be null - avoid NPE
if (!running) {
return false;
}
getExecutor().execute(new SocketProcessor(wrapper));
} catch (RejectedExecutionException x) {
log.warn(“Socket processing request was rejected for:”+socket,x);
return false;
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
// This means we got an OOM or similar creating a thread, or that
// the pool and its queue are full
log.error(sm.getString(“endpoint.process.fail”), t);
return false;
}
return true;
}
protected class SocketProcessor implements Runnable {
protected SocketWrapper<Socket> socket = null;
protected SocketStatus status = null;
public SocketProcessor(SocketWrapper<Socket> socket) {
if (socket==null) throw new NullPointerException();
this.socket = socket;
}
this(socket);
this.status = status;
}
public void run() {
boolean launch = false;
synchronized (socket) {
try {
SocketState state = SocketState.OPEN;
// SSL handshake
serverSocketFactory.handshake(socket.getSocket());
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
if (log.isDebugEnabled()) {
log.debug(sm.getString(“endpoint.err.handshake”), t);
}
// Tell to close the socket
state = SocketState.CLOSED;
}
if ( (state != SocketState.CLOSED) ) {
state = (status==null)?handler.process(socket):handler.process(socket,status);
}
if (state == SocketState.CLOSED) {
// Close socket
if (log.isTraceEnabled()) {
log.trace(“Closing socket:”+socket);
}
countDownConnection();
try {
socket.getSocket().close();
} catch (IOException e) {
// Ignore
}
} else if (state == SocketState.ASYNC_END ||
state == SocketState.OPEN){
socket.setKeptAlive(true);
socket.access();
launch = true;
} else if (state == SocketState.LONG) {
socket.access();
waitingRequests.add(socket);
}
} finally {
if (launch) {
try {
getExecutor().execute(new SocketProcessor(socket, SocketStatus.OPEN));
} catch (NullPointerException npe) {
if (running) {
log.error(sm.getString(“endpoint.launch.fail”),
npe);
}
}
}
}
}
socket = null;
// Finish up this request
}
}
protected class AsyncTimeout implements Runnable {
@Override
public void run() {
// Loop until we receive a shutdown command
while (running) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// Ignore
}
long now = System.currentTimeMillis();
Iterator<SocketWrapper<Socket>> sockets =
waitingRequests.iterator();
while (sockets.hasNext()) {
SocketWrapper<Socket> socket = sockets.next();
long access = socket.getLastAccess();
if ((now-access)>socket.getTimeout()) {
processSocketAsync(socket,SocketStatus.TIMEOUT);
}
}
// Loop if endpoint is paused
while (paused && running) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// Ignore
}
}
}
}
}
- Tomcat 源码学习之JIoEndpoint
- Tomcat 源码学习之JIoEndpoint
- Tomcat学习之源码编译
- Tomcat学习之源码编译
- Tomcat学习之源码编译
- org.apache.tomcat.util.net.JIoEndpoint$Acceptor run(转)
- Java学习篇之---研究tomcat源码
- Tomcat源码学习之源码调试环境搭建
- JIoEndpoint类
- org.apache.tomcat.util.net.JIoEndpoint createWorkerThread Tomcat连接线程超出
- Tomcat源码学习
- Tomcat源码学习
- Tomcat源码学习
- Tomcat源码编译学习
- Tomcat源码学习
- Tomcat源码学习
- Tomcat源码学习笔记
- tomcat源码学习一
- 8位数码管动态扫描显示变化数据
- POJ 1094 Sorting It All Out (拓扑排序)
- centos配置ssh无密码访问
- POJ2253-Frogger(Dijkstra变式)
- Spring Web MVC和Hibernate的集成
- Tomcat 源码学习之JIoEndpoint
- 【C++基础概念】有关指针、引用的几个问题
- CentOS7 桌面环境的大小
- MongoDB 文档字段增删改
- Android三种基本的加载网络图片方式
- iOS KVO监听
- Tomcat 工作原理
- Mahmoud and a Dictionary codeforces396 div2 D
- kindeditor保存图片路径