一、tomat启动流程

1、启动HttpConnector

  connector等待连接请求,只负责接受socket请求,具体处理过程交给HttpProcessor处理。

  tomcat用户只能访问到connector,能设置接受的数据的buffer大小,而不能看见HttpProcessor的处理过程。

2、创建HttpProcessor对象池

  创建对象后马上调用start()方法启动processor的线程:

    private HttpProcessor newProcessor() {
HttpProcessor processor = new HttpProcessor(this, curProcessors++);
if (processor instanceof Lifecycle) {
try {
((Lifecycle) processor).start();
} catch (LifecycleException e) {
log("newProcessor", e);
return (null);
}
}
created.addElement(processor);
return (processor);
}

  创建对象池:

    private HttpProcessor createProcessor() {

        synchronized (processors) {
if (processors.size() > 0) {
return ((HttpProcessor) processors.pop());
}
if ((maxProcessors > 0) && (curProcessors < maxProcessors)) {
return (newProcessor());
} else {
if (maxProcessors < 0) {
return (newProcessor());
} else {
return (null);
}
}
}

3、等待客户端请求,对每个请求启动一个线程,并取出一个processor来处理这个socket

    public void run() {
// Loop until we receive a shutdown command
while (!stopped) {
// Accept the next incoming connection from the server socket
Socket socket = null;
try {
socket = serverSocket.accept();
if (connectionTimeout > 0)
socket.setSoTimeout(connectionTimeout);
socket.setTcpNoDelay(tcpNoDelay);
} catch (AccessControlException ace) {
log("socket accept security exception", ace);
continue;
} catch (IOException e) {
try {
synchronized (threadSync) {
if (started && !stopped)
log("accept error: ", e);
if (!stopped) {
serverSocket.close();
serverSocket = open();
}
}
} catch ...continue;
} // Hand this socket off to an appropriate processor
HttpProcessor processor = createProcessor();
if (processor == null) {
try {
log(sm.getString("httpConnector.noProcessor"));
socket.close();
} catch (IOException e) {
;
}
continue;
}
processor.assign(socket);
}
synchronized (threadSync) {
threadSync.notifyAll();
}
}

  在connector的run()里面创建了processor对象池,创建processor的时候就启动了processor线程。但这时候所有的processor一直在阻塞着,因为没有等到要处理的socket对象。

  一旦有了一个新的socket请求,就把这个socket交给一个processor来处理,这里调用了processor.assign(socket)方法,用于processor里面的同步处理。

4、具体处理socket请求的http的url、head、cookie等

  这些处理过程在processor的process()方法里面处理,并把这些信息封装到request对象和response对象。

5、 交给特定的servlet处理业务逻辑

  process()方法里面有一行代码:

                if (ok) {
connector.getContainer().invoke(request, response);
}

  如果都处理正常,就交给对应的容器container去处理。

  invoke()方法里面,实例化一个ClassLoader对象,去加载指定的servlet的class文件,然后调用这个servlet的service方法等。

二、HttpConnector和HttpProcessor的同步配合

  HttpConnector初始化的的时候,建立了一系列的HttpProcessor,放在属性变量栈中。
  当获取到一个客户端的连接socket的时候,就会去获取一个processor,并且调用processor的assign方法,将该socket传递给这个processor。
  这个是在connector的线程里做的。

  先看下processor的assign方法:

/**
* Process an incoming TCP/IP connection on the specified socket. Any
* exception that occurs during processing must be logged and swallowed.
* <b>NOTE</b>: This method is called from our Connector's thread. We
* must assign it to our own thread so that multiple simultaneous
* requests can be handled.
*
* @param socket TCP socket to process
*/
synchronized void assign(Socket socket) {
// 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;
available = true;
notifyAll();
}

  这个方法是同步方法。一开始的时候,这个available是false的,因此,connector线程调用这个assign方法,不会陷入等待状态。而是顺序执行:

   this.socket = socket;
available = true;
notifyAll();

  这个notifyAll()起到什么作用呢?这个要先看Processor的run方法:

 /**
* 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 (!stopped) {
// Wait for the next socket to be assigned
Socket socket = await();
if (socket == null)
continue;
// Process the request from this socket
try {
process(socket);
} catch (Throwable t) {
log("process.invoke", t);
}
// Finish up this request
connector.recycle(this);
}
// Tell threadStop() we have shut ourselves down successfully
synchronized (threadSync) {
threadSync.notifyAll();
}
}

  看这一句:

  // Wait for the next socket to be assigned
Socket socket = await();

  大概可以猜到在等待获得一个socket,继续看await方法:

 /**
* Await a newly assigned Socket from our Connector, or <code>null</code>
* if we are supposed to shut down.
*/
private synchronized Socket 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
Socket socket = this.socket;
available = false;
notifyAll();
if ((debug >= 1) && (socket != null))
log(" The incoming request has been awaited");
return (socket);
}

  这个await在等待一个socekt,当没有socket可以获取的时候,即available=false,也即是初始状态,这个await方法会调用wait(),导致运行该run方法的processor线程陷入等待。
什么时候这个processor线程才被唤醒?就是我们在assign方法里的notifyAll方法了。当这个processor线程被唤醒后,检查while循环的条件:while(!available),显然,此时available是true的,那么就会退出循环(即不进入等待),进而执行以下的代码:

   Socket socket = this.socket;
available = false;
notifyAll();

  即将processor实例的socket对象(在assign方法里得到的),赋给一个局部变量,这样就把processor对象的实例变量解放了,可以用来接收新的socket。接收了这个socket以后,就把available重新设置为false,即connector线程给的socket已经被处理了。

  从概念上来理解整个过程:
  一开始,processor在等待资源,connector负责提供资源。当connector得到一个资源的时候,会随机抽到一个processor,然后,将此资源给processor对象,并且通知所有processor对象“有资源啦”,所有processor都为之精神一震,都赶快去检查,结果只有一个确实得到了资源,可以干活了,另外的processor发现资源没有给自己,于是又继续等待。就是这样的过程。

三、一些疑问

  1、对于assign方法里面的:

  this.socket = socket;

  和awai方法里面的:

Socket socket = this.socket;

  难于理解。

  就是:为什么 await 需要使用一个本地变量(socket)而不是返回实例的 socket 变量呢?

  因为这样一来,在当前 socket 被完全处理之前,实例的 socket 变量可以赋给下一个前来的 socket

Reference

1、How Tomcat Works

2、http://biancheng.dnbcw.info/java/76523.html

3、http://hi.baidu.com/brightming2/item/bc6107f8fa734412e3e3bd45

Tomcat学习 HttpConnector和HttpProcessor启动流程和线程交互的更多相关文章

  1. 女儿拿着小天才电话手表问我App启动流程

    前言 首先,new一个女儿, var mDdaughter = new 女儿("6岁","漂亮可爱","健康乖巧","最喜欢玩小天 ...

  2. Tomcat源码分析(从启动流程到请求处理)

    Tomcat 8.5下载地址 https://tomcat.apache.org/download-80.cgi Tomcat启动流程 Tomcat源码目录 catalina目录 catalina包含 ...

  3. Tomcat源码分析之—具体启动流程分析

    从Tomcat启动调用栈可知,Bootstrap类的main方法为整个Tomcat的入口,在init初始化Bootstrap类的时候为设置Catalina的工作路径也就是Catalina_HOME信息 ...

  4. Android FM模块学习之一 FM启动流程

    最近在学习FM模块,FM是一个值得学习的模块,可以从上层看到底层. 上层就是FM的按扭操作和界面显示,从而调用到FM底层驱动来实现广播收听的功能. FM启动流程:如下图: 先进入FMRadio.jav ...

  5. ASP.NET Core MVC 源码学习:MVC 启动流程详解

    前言 在 上一篇 文章中,我们学习了 ASP.NET Core MVC 的路由模块,那么在本篇文章中,主要是对 ASP.NET Core MVC 启动流程的一个学习. ASP.NET Core 是新一 ...

  6. 理解Tomcat架构、启动流程及其性能优化

    PS:but, it's bullshit ! 备注:实话说,从文档上扒拉的,文档地址:在每一个Tomcat安装目录下,会有一个webapps文件夹,里面有一个docs文件夹,点击index.html ...

  7. nginx学习十一 nginx启动流程

    今天用了一天的时间看nginx的启动流程,流程还是非常复杂.基本的函数调用有十几个之多.通过看源代码和上网查资料,弄懂了一些函数.有些函数还在学习中,有些函数还待日后学习,这里记录一下今天所学.加油! ...

  8. activiti学习6:启动流程后动态获取流程图

    目录 activiti学习6:启动流程后动态获取流程图 一.绘图原理 二.根据流程定义id绘图 三.根据流程实例id绘图 3.1 基本原理 3.2 当前节点的获取 3.3 走过的节点的获取 3.4 绘 ...

  9. Tomcat启动流程简析

    Tomcat是一款我们平时开发过程中最常用到的Servlet容器.本系列博客会记录Tomcat的整体架构.主要组件.IO线程模型.请求在Tomcat内部的流转过程以及一些Tomcat调优的相关知识. ...

随机推荐

  1. ecshop lang用法

    ecshop lang用法 分类: ECSHOP2013-08-15 16:17 2184人阅读 评论(0) 收藏 举报 ecshop目录下的languages目录.这个是ecshop语言包所在.ec ...

  2. MZhong's Resume

    MATTHEW.ZHONG Male,27 Age Front-End Developer matthew.zhong@morningstar.com OBJECTIVE My objective i ...

  3. TeamViewer“试用期已到期”解决方法

    今天打开TeamViewer,显示试用期已到期,不能远程至其它电脑上.软件重装也没用,因为它与你的机器及网卡做了绑定. 查看网上资料,发现需要删除注册信息等操作才能继续使用,步骤如下: 说明:操作前, ...

  4. linux下搭建SVN服务器完全手册【摘抄】

    系统环境        RHEL5.4最小化安装(关iptables,关selinux) + ssh + yum 一,安装必须的软件包.        yum install subversion ( ...

  5. json 增删改 加 排序

    <script type="text/javascript"> var json = { "age":24, "name":&q ...

  6. 备份mysql

    #!/bin/bash # 要备份的数据库名,多个数据库用空格分开USER=rootPASSWORD=rootdatabases=("shopnc") # 备份文件要保存的目录ba ...

  7. php---实现保留小数点后两位

    PHP 中的 round() 函数可以实现 round() 函数对浮点数进行四舍五入. round(x,prec) 参数说明x 可选.规定要舍入的数字.prec 可选.规定小数点后的位数. 返回将 x ...

  8. [LeetCode]题解(python):107 Binary Tree Level Order Traversal II

    题目来源 https://leetcode.com/problems/binary-tree-level-order-traversal-ii/ Given a binary tree, return ...

  9. Linux some command(continue...)

    挂载硬盘 sudo mount -t ext4 /dev/sdb1 /media/hadoop 自动挂载相关 sudo blkid sudo fdisk -l vim /etc/fstab cat / ...

  10. iOS 冒泡排序

    //冒泡排序 -(NSArray*)Bubble_Sort:(NSArray*)oldArray { NSMutableArray * newArray = [NSMutableArray array ...