Tomcat 的启动化过程分析(三)_tomcat 启动事加锁-程序员宅基地

技术标签: tomcat  Tomcat 源码分析  

介绍

该笔记是在学习拉勾教育 Java 高薪训练营后,结合课程和老师的视频,自己跟踪源码后做的笔记。

Bootstrap#load

使用反射调用 Catalina 实例的 load 方法,即 Catalina.load()。

    private void load(String[] arguments) throws Exception {
    

        // Call the load() method
        String methodName = "load";
        Object param[];
        Class<?> paramTypes[];
        if (arguments==null || arguments.length==0) {
    
            paramTypes = null;
            param = null;
        } else {
    
            paramTypes = new Class[1];
            paramTypes[0] = arguments.getClass();
            param = new Object[1];
            param[0] = arguments;
        }
        // 根据方法名和参数获取 load 方法
        Method method =
            catalinaDaemon.getClass().getMethod(methodName, paramTypes);
        if (log.isDebugEnabled()) {
    
            log.debug("Calling startup class " + method);
        }
        // 调用 Catalina 实例的 load 方法,即 Catalina.load()
        method.invoke(catalinaDaemon, param);
    }

Catalina#load()

Tomcat 的 server.xml 结构如下,最外层结构是 Server,所以会先解析 Server,进行初始化。然后在由 Server 来调用其他组件的初始化,达到一键初始化的目的。

<Server>
    <Service>
        <Connector />
        <Connector />
        <Engine>
            <Host>
                <Context />
            </Host>
        </Engine>
    </Service>
</Server>
  • 创建解析器,用于解析 xml 配置文件,获取 conf/server.xml 文件的流;
  • getServer().init(),获取 server,进行初始化,使用模板方法设计模式,调用的是 StandardServer#initInternal。
    public void load() {
    

        if (loaded) {
    
            return;
        }
        loaded = true;

        long t1 = System.nanoTime();

        initDirs();

        // Before digester - it may be needed
        // 命名服务
        initNaming();

        // Create and execute our Digester
        // 创建解析器,用于解析 xml 配置文件,比如解析 server.xml
        Digester digester = createStartDigester();

        InputSource inputSource = null;
        InputStream inputStream = null;
        File file = null;
        try {
    
            try {
    
                // 获取 conf/server.xml 文件的流
                file = configFile();
                inputStream = new FileInputStream(file);
                inputSource = new InputSource(file.toURI().toURL().toString());
            } catch (Exception e) {
    
                if (log.isDebugEnabled()) {
    
                    log.debug(sm.getString("catalina.configFail", file), e);
                }
            }
            
            // ...

            try {
    
                inputSource.setByteStream(inputStream);
                digester.push(this);
                // 解析配置文件 conf/server.xml 的流
                digester.parse(inputSource);
            } catch (SAXParseException spe) {
    
                log.warn("Catalina.start using " + getConfigFile() + ": " +
                        spe.getMessage());
                return;
            } catch (Exception e) {
    
                log.warn("Catalina.start using " + getConfigFile() + ": " , e);
                return;
            }
        } finally {
    
            if (inputStream != null) {
    
                try {
    
                    inputStream.close();
                } catch (IOException e) {
    
                    // Ignore
                }
            }
        }

        getServer().setCatalina(this);
        getServer().setCatalinaHome(Bootstrap.getCatalinaHomeFile());
        getServer().setCatalinaBase(Bootstrap.getCatalinaBaseFile());

        // Stream redirection
        initStreams();

        // Start the new server
        try {
    
            // 获取 server,进行初始化,使用模板方法设计模式,调用的是 StandardServer#initInternal
            getServer().init();
        } 
        
        // ...
    }

StandardServer#initInternal

遍历列表 services,调用 service.init() 方法,一个 Server 包含多个 Service。

    private Service services[] = new Service[0];

    @Override
    protected void initInternal() throws LifecycleException {
    

        super.initInternal();

        // ...
        // Initialize our defined Services
        // 遍历 Service,调用其初始化方法,一个 Server 有多个 Service
        for (int i = 0; i < services.length; i++) {
    
            services[i].init();
        }
    }

StandardService#initInternal

调用多个组件 engine、executor、connector 等组件的 init() 方法。

    private final Object connectorsLock = new Object();

    @Override
    protected void initInternal() throws LifecycleException {
    

        super.initInternal();

        if (engine != null) {
    
            engine.init();
        }

        // Initialize any Executors
        for (Executor executor : findExecutors()) {
    
            if (executor instanceof JmxEnabled) {
    
                ((JmxEnabled) executor).setDomain(getDomain());
            }
            executor.init();
        }

        // Initialize mapper listener
        mapperListener.init();

        // Initialize our defined Connectors
        // 遍历 connector 时,加锁
        synchronized (connectorsLock) {
    
            for (Connector connector : connectors) {
    
                try {
    
                    connector.init();
                } catch (Exception e) {
    
                    String message = sm.getString(
                            "standardService.connector.initFailed", connector);
                    log.error(message, e);

                    if (Boolean.getBoolean("org.apache.catalina.startup.EXIT_ON_INIT_FAILURE"))
                        throw new LifecycleException(message);
                }
            }
        }
    }

StandardEngine#initInternal

调用父类 LifecycleMBeanBase 的 initInternal 方法。

    @Override
    protected void initInternal() throws LifecycleException {
    
        // Ensure that a Realm is present before any attempt is made to start
        // one. This will create the default NullRealm if necessary.
        getRealm();
        super.initInternal();
    }

StandardThreadExecutor#initInternal

调用父类 LifecycleMBeanBase 的 initInternal 方法。

    @Override
    protected void initInternal() throws LifecycleException {
    
        super.initInternal();
    }

Connector#initInternal

设置适配器和进行端口绑定。

  • CoyoteAdapter,适配器,用于将 Request 转换为 ServletRequest,this 为当前 connector;
  • protocolHandler.init(),会调用 AbstractEndpoint 的 init() 方法,进行端口绑定。
    @Override
    protected void initInternal() throws LifecycleException {
    

        super.initInternal();

        // Initialize adapter
        // 初始化适配器,用于将 Request 转换为 ServletRequest,this 为当前 connector
        adapter = new CoyoteAdapter(this);
        protocolHandler.setAdapter(adapter);

        // ...

        try {
    
            protocolHandler.init();
        } catch (Exception e) {
    
            throw new LifecycleException(
                    sm.getString("coyoteConnector.protocolHandlerInitializationFailed"), e);
        }
    }

AbstractProtocol#init

主要为调用 AbstractEndpoint 的 init() 方法,进行端口绑定。

    @Override
    public void init() throws Exception {
    
        // ... 

        String endpointName = getName();
        endpoint.setName(endpointName.substring(1, endpointName.length()-1));
        endpoint.setDomain(domain);

        endpoint.init();
    }

AbstractEndpoint#init

核心方法为 bind(),进行端口绑定。

    public void init() throws Exception {
    
        if (bindOnInit) {
    
            // 端口绑定,默认为 NioEndPoint
            bind();
            bindState = BindState.BOUND_ON_INIT;
        }
        // ...
    }

NioEndPoint#bind

  • ServerSocketChannel.open(),调用底层 NIO 的 api,获取服务端的 Socket,进行端口绑定;
  • selectorPool.open(),用于接收客户端的连接。
    @Override
    public void bind() throws Exception {
    

        if (!getUseInheritedChannel()) {
    
            // 调用底层 NIO 的 api,获取服务端的 Socket
            serverSock = ServerSocketChannel.open();
            socketProperties.setProperties(serverSock.socket());
            // 根据 IP 和端口构造地址
            InetSocketAddress addr = (getAddress()!=null?new InetSocketAddress(getAddress(),getPort()):new InetSocketAddress(getPort()));
            // 绑定端口,比如 8080
            serverSock.socket().bind(addr,getAcceptCount());
        } else {
    
            // Retrieve the channel provided by the OS
            Channel ic = System.inheritedChannel();
            if (ic instanceof ServerSocketChannel) {
    
                serverSock = (ServerSocketChannel) ic;
            }
            if (serverSock == null) {
    
                throw new IllegalArgumentException(sm.getString("endpoint.init.bind.inherited"));
            }
        }
        serverSock.configureBlocking(true); //mimic APR behavior

        // ...

        // 用于接收客户端的连接
        selectorPool.open();
    }

NioSelectorPool#open

接收客户端的连接。

    public void open() throws IOException {
    
        enabled = true;
        getSharedSelector();
        if (SHARED) {
    
            blockingSelector = new NioBlockingSelector();
            blockingSelector.open(getSharedSelector());
        }
    }
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/qq_32045991/article/details/107894396

智能推荐

c语言十六实验答案,《C语言》上机实验题及参考答案-程序员宅基地

文章浏览阅读1.6k次。C语言编程题精选1、 编程实现对键盘输入的英文名句子进行加密。用加密方法为,当内容为英文字母时其在26字母中的其后三个字母代替该字母,若为其它字符时不变。 2、 编程实现将任意的十进制整数转换成R进制数(R在2-16之间)。3、 从键盘输入一指定金额(以元为单位,如345.78),然后显示支付该金额的各种面额人民币数量,要求显示100元、50元、10元、5元、2元、1元、5角、1角、5分、1分各多..._istudy c语言 实验16课内实践16-综合练习

PhD English Research —— Writing_phd english class 研究-程序员宅基地

文章浏览阅读137次。English Research Writing_phd english class 研究

计算机学校有什么课程设计,局域网课程设计怎么做?-程序员宅基地

文章浏览阅读294次。校园网规划摘要 : 本文通过对校园园区局域网(以下简称校园园区网)规划思想过程的论述,对就如何建立一个高效,安全的校园网提供设计思想和组网步骤依据。关键词:网络需求,规划实施计划0. 引言信息技术日新月异的今天,网络技术发展迅猛,信息传输已经不仅仅局限于单纯文本数据,数字数据的传输,随之而来的是视频,音频等多媒体技术的广泛运用。随着技术的发展,网络设备性能和传输介质容量有了极大的提高,但是由于用户..._计算机的课设咋做嘛?

C++数据结构-高效排序算法_c++如何对数组值进行排序效率最高-程序员宅基地

文章浏览阅读817次。对于基本的几种排序方法:插入,选择,冒泡。他们的复杂度均为O(n2)。算法运行所需时间增加的速度通常比数组本身增加的速度要快。希尔排序通过将原数组分为及几个子数组,先分别将这几个子数组排序,再把排序好的子数组进行排序,可以大大提高效率,排序方法可使用任意简单排序,这里使用插入排序用伪代码来表示对于h的值的把控,是需要思考的问题。如果h过大,子数组就会过多,即使子数组已经排序好,也无法显著提高效率;反之,如果h过小,子数组的元素就会过多,算法效率也会降低。_c++如何对数组值进行排序效率最高

mysql竖表转横表,横表转竖表_mysql竖表变横表-程序员宅基地

文章浏览阅读1.9k次,点赞2次,收藏9次。SELECT p.姓名p.语文,p.数学,p.英语 from score as a pivot(sum(成绩) for 课程 in(语文,数学,英语)) as p;查询第一行数据,当查询课程列的内容为'语文'时候,then'语文'这个值变为它对应成绩值60,起列名为语文。--竖表转行表使用pivot(这个是sqlserver,mysql不可以使用)第二行数据,课程值为‘数学’时,then'数学'变为70,起列名为数学。无论是横转竖,还是竖转横,原表都不变还是原来的样子。score2,此表为横表。_mysql竖表变横表

【编程马拉松】【019-一笔画】_一笔作画游戏 csdn-程序员宅基地

文章浏览阅读2.6k次。咱们来玩一笔画游戏吧,规则是这样的:有一个连通的图,能否找到一个恰好包含了所有的边,并且没有重复的路径。输入包含多组数据。每组数据的第一行包含两个整数n和m (2≤n, m≤1000),其中n是顶点的个数,m是边的条数。紧接着有m行,每行包含两个整数from和to (1 ≤ from, to ≤ n, from != to),分别代表边的两端顶点。边是双向的,并且两个顶点之间可能不止一条边_一笔作画游戏 csdn

随便推点

为JSF定做的应用程序框架(一)-程序员宅基地

文章浏览阅读142次。JavaServer Faces (JSF) 是用于 Java Web 应用程序的第一个标准化的用户界面框架。 而 Seam 是一个扩展 JSF 的强大的应用程序框架。在这个由三部分组成的新系列中的第一篇文章中,发现这两种框架之间的互补性。Dan Allen 介绍了 Seam 对 JSF 生命周期的增强,包括上下文状态管理、 RESTful URL、Ajax remoting、适当的异常..._jsf界面框架颜色怎么弄

Django在根据models生成数据库表时报 __init__() missing 1 required positional argument: 'on_delete'...-程序员宅基地

文章浏览阅读115次。code: 1 #encoding=utf-8 2 from django.db import models 3 # Create your models here. 4 class BookInfo(models.Model): #创建书本信息类,继承models.Model 5 booktitle=models.CharField(max_length=20)..._book = models.foreignkey(oenpageinfo) typeerror: __init__() missing 1 requir

Please use a locale setting which supports utf-8_python can't change the filesystem locale after lo-程序员宅基地

文章浏览阅读5.1k次,点赞3次,收藏8次。原地址:https://wiki.yoctoproject.org/wiki/TipsAndTricks/ResolvingLocaleIssuesWhat to do when bitbake says " Sad Locale, Need UTF-8"If bitbake says:Please use a locale setting which supports utf-8..._python can't change the filesystem locale after loading so we need a utf-8 w

在bochs虚拟机中安装WindowsXP (学习)_bochs xp-程序员宅基地

文章浏览阅读9.2k次。好吧话不多说,开始安装 WIndowsXP1、下载安装bochs……(这步不会的下面可以不用看了……)2、在Bochs安装目录中创建一个WinXP文件夹(同上面的括号)3、创建虚拟硬盘用于存放WinXP镜像具体步骤:进入命令提示符,使用bximage工具生成image需要回答几个问题一:生成硬盘还是软盘二:镜像类型 flat sparse or growing三_bochs xp

vue项目实现导航栏吸顶功能_vue吸顶导航栏-程序员宅基地

文章浏览阅读478次。建立判断条件,如果页面滚动的值超过导航栏的高度navHeight时,将导航栏的position属性值改为fixed,top值可以设置为0px。当页面回到顶端时,需要再次显示为原来默认的状态,所以把导航栏的position值改为默认的static。调用窗口滚动对象window.onscroll事件。当滚动页面的滚动条时会触发scroll里的事件方法。_vue吸顶导航栏

Visual Studio 2008简体中文试用版(90天)变成永久正式版的两种方法-程序员宅基地

文章浏览阅读176次。Visual Studio 2008简体中文试用版(90天)变成永久正式版的两种方法: 一、先安装试用版,然后在“添加或删除程序”里找到VS2008,点“更改/删除”就会看到一个输入序列号的地方,把序列号输进去,点“升级”按钮即可,Team Suite和Professional通用。 二、用UltraISO打开VS的ISO安装文件,把Setup\setup.sdb文件解压缩出来,一定记得..._xmq2y4t3v6xj48yd3k2v6c4wt

推荐文章

热门文章

相关标签