当前位置:   article > 正文

(三)Tomcat源码阅读:Server组件分析_private service[] services = new service[0];

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

一、概述

打开tomcat源码找到server类,我们可以从开头的注释获取一些主要信息。

我对下面的注释进行概述:Server是顶级元素,并且实现了Lifecycle接口,例如start和stop方法。

/**
 * A <code>Server</code> element represents the entire Catalina
 * servlet container.  Its attributes represent the characteristics of
 * the servlet container as a whole.  A <code>Server</code> may contain
 * one or more <code>Services</code>, and the top level set of naming
 * resources.
 * <p>
 * Normally, an implementation of this interface will also implement
 * <code>Lifecycle</code>, such that when the <code>start()</code> and
 * <code>stop()</code> methods are called, all of the defined
 * <code>Services</code> are also started or stopped.
 * <p>
 * In between, the implementation must open a server socket on the port number
 * specified by the <code>port</code> property.  When a connection is accepted,
 * the first line is read and compared with the specified shutdown command.
 * If the command matches, shutdown of the server is initiated.
 * <p>
 * <strong>NOTE</strong> - The concrete implementation of this class should
 * register the (singleton) instance with the <code>ServerFactory</code>
 * class in its constructor(s).
 *
 * @author Craig R. McClanahan
 */

二、阅读源码

源码阅读中,我的一般顺序是这样:接口->抽象类->实现类(子类)。因为位于比较高级的类,越能对项目进行概览,并能从大到小对项目进行分析,不容易掉进牛角尖。当然具体的过程还要具体分析,不一定死套这个顺序。接下我们就按照Lifecycle->Server->StandardServer的顺序进行阅读。

 (一)Lifecycle

1、类注释

Lifecycle这个类为容器定义了统一的生命周期的方法,例如:启动,停止等。下面的图片表明了声明周期之间相互转化的流程。也就是所有容器都实现了生命周期的方法。

/**
 * Common interface for component life cycle methods.  Catalina components
 * may implement this interface (as well as the appropriate interface(s) for
 * the functionality they support) in order to provide a consistent mechanism
 * to start and stop the component.
 * <br>
 * The valid state transitions for components that support {@link Lifecycle}
 * are:
 * <pre>
 *            start()
 *  -----------------------------
 *  |                           |
 *  | init()                    |
 * NEW -»-- INITIALIZING        |
 * | |           |              |     ------------------«-----------------------
 * | |           |auto          |     |                                        |
 * | |          \|/    start() \|/   \|/     auto          auto         stop() |
 * | |      INITIALIZED --»-- STARTING_PREP --»- STARTING --»- STARTED --»---  |
 * | |         |                                                            |  |
 * | |destroy()|                                                            |  |
 * | --»-----«--    ------------------------«--------------------------------  ^
 * |     |          |                                                          |
 * |     |         \|/          auto                 auto              start() |
 * |     |     STOPPING_PREP ----»---- STOPPING ------»----- STOPPED -----»-----
 * |    \|/                               ^                     |  ^
 * |     |               stop()           |                     |  |
 * |     |       --------------------------                     |  |
 * |     |       |                                              |  |
 * |     |       |    destroy()                       destroy() |  |
 * |     |    FAILED ----»------ DESTROYING ---«-----------------  |
 * |     |                        ^     |                          |
 * |     |     destroy()          |     |auto                      |
 * |     --------»-----------------    \|/                         |
 * |                                 DESTROYED                     |
 * |                                                               |
 * |                            stop()                             |
 * ----»-----------------------------»------------------------------
 *
 * Any state can transition to FAILED.
 *
 * Calling start() while a component is in states STARTING_PREP, STARTING or
 * STARTED has no effect.
 *
 * Calling start() while a component is in state NEW will cause init() to be
 * called immediately after the start() method is entered.
 *
 * Calling stop() while a component is in states STOPPING_PREP, STOPPING or
 * STOPPED has no effect.
 *
 * Calling stop() while a component is in state NEW transitions the component
 * to STOPPED. This is typically encountered when a component fails to start and
 * does not start all its sub-components. When the component is stopped, it will
 * try to stop all sub-components - even those it didn't start.
 *
 * Attempting any other transition will throw {@link LifecycleException}.
 *
 * </pre>
 * The {@link LifecycleEvent}s fired during state changes are defined in the
 * methods that trigger the changed. No {@link LifecycleEvent}s are fired if the
 * attempted transition is not valid.
 *
 * @author Craig R. McClanahan
 */

2、常量

这里主要定义了生命周期中定义的一些常量,了解即可

  1. // ----------------------------------------------------- Manifest Constants
  2. /**
  3. * The LifecycleEvent type for the "component before init" event.
  4. */
  5. String BEFORE_INIT_EVENT = "before_init";
  6. /**
  7. * The LifecycleEvent type for the "component after init" event.
  8. */
  9. String AFTER_INIT_EVENT = "after_init";
  10. /**
  11. * The LifecycleEvent type for the "component start" event.
  12. */
  13. String START_EVENT = "start";
  14. /**
  15. * The LifecycleEvent type for the "component before start" event.
  16. */
  17. String BEFORE_START_EVENT = "before_start";
  18. /**
  19. * The LifecycleEvent type for the "component after start" event.
  20. */
  21. String AFTER_START_EVENT = "after_start";
  22. /**
  23. * The LifecycleEvent type for the "component stop" event.
  24. */
  25. String STOP_EVENT = "stop";
  26. /**
  27. * The LifecycleEvent type for the "component before stop" event.
  28. */
  29. String BEFORE_STOP_EVENT = "before_stop";
  30. /**
  31. * The LifecycleEvent type for the "component after stop" event.
  32. */
  33. String AFTER_STOP_EVENT = "after_stop";
  34. /**
  35. * The LifecycleEvent type for the "component after destroy" event.
  36. */
  37. String AFTER_DESTROY_EVENT = "after_destroy";
  38. /**
  39. * The LifecycleEvent type for the "component before destroy" event.
  40. */
  41. String BEFORE_DESTROY_EVENT = "before_destroy";
  42. /**
  43. * The LifecycleEvent type for the "periodic" event.
  44. */
  45. String PERIODIC_EVENT = "periodic";
  46. /**
  47. * The LifecycleEvent type for the "configure_start" event. Used by those
  48. * components that use a separate component to perform configuration and
  49. * need to signal when configuration should be performed - usually after
  50. * {@link #BEFORE_START_EVENT} and before {@link #START_EVENT}.
  51. */
  52. String CONFIGURE_START_EVENT = "configure_start";
  53. /**
  54. * The LifecycleEvent type for the "configure_stop" event. Used by those
  55. * components that use a separate component to perform configuration and
  56. * need to signal when de-configuration should be performed - usually after
  57. * {@link #STOP_EVENT} and before {@link #AFTER_STOP_EVENT}.
  58. */
  59. String CONFIGURE_STOP_EVENT = "configure_stop";

不得不说tomcat中编码是比较规范的,在常量的地方标记常量,在方法的地方标记方法,这是我们要xue

3、方法

方法介绍中我们就忽略掉不太重要的方法找比较重要的方法进行介绍。下面这四个方法定义了容器从初始化到销毁的过程,为什么我会把它选为重要方法,因为开头的类注释就说明了,这个类的作用就是定义容器的生命周期,因此这四个对应生命周期的方法比较重要。

  1. void init() throws LifecycleException;
  2. void start() throws LifecycleException;
  3. void stop() throws LifecycleException;
  4. void destroy() throws LifecycleException;

(二)Server

1、类注释

这部分主要说明了Server是整个tomcat组件的顶层,如果它停止了它下面的组件都会停止,并且它实现了生命周期。

/**
 * A <code>Server</code> element represents the entire Catalina
 * servlet container.  Its attributes represent the characteristics of
 * the servlet container as a whole.  A <code>Server</code> may contain
 * one or more <code>Services</code>, and the top level set of naming
 * resources.
 * <p>
 * Normally, an implementation of this interface will also implement
 * <code>Lifecycle</code>, such that when the <code>start()</code> and
 * <code>stop()</code> methods are called, all of the defined
 * <code>Services</code> are also started or stopped.
 * <p>
 * In between, the implementation must open a server socket on the port number
 * specified by the <code>port</code> property.  When a connection is accepted,
 * the first line is read and compared with the specified shutdown command.
 * If the command matches, shutdown of the server is initiated.
 * <p>
 * <strong>NOTE</strong> - The concrete implementation of this class should
 * register the (singleton) instance with the <code>ServerFactory</code>
 * class in its constructor(s).
 *
 * @author Craig R. McClanahan
 */

(三)StandardServer 

StandardServer继承了LifecycleMBeanBase类但是我们无需去深究LifecycleMBeanBase类,因为LifecycleMBeanBase是做监控用的,我们现在的任务是理清大概流程,因此不用深究LifecycleMBeanBase,只需要了解StandardServer即可。

1、主要方法

addService

  1. @Override
  2. public void addService(Service service) {
  3. service.setServer(this);
  4. //加锁并通过动态数组的方式添加service
  5. synchronized (servicesLock) {
  6. Service results[] = new Service[services.length + 1];
  7. System.arraycopy(services, 0, results, 0, services.length);
  8. results[services.length] = service;
  9. services = results;
  10. if (getState().isAvailable()) {
  11. try {
  12. service.start();
  13. } catch (LifecycleException e) {
  14. // Ignore
  15. }
  16. }
  17. //将添加service的事件发给监听器
  18. support.firePropertyChange("service", null, service);
  19. }
  20. }
  1. @Override
  2. public void removeService(Service service) {
  3. //加锁将对象移除
  4. synchronized (servicesLock) {
  5. int j = -1;
  6. for (int i = 0; i < services.length; i++) {
  7. if (service == services[i]) {
  8. j = i;
  9. break;
  10. }
  11. }
  12. if (j < 0) {
  13. return;
  14. }
  15. try {
  16. services[j].stop();
  17. } catch (LifecycleException e) {
  18. // Ignore
  19. }
  20. int k = 0;
  21. Service results[] = new Service[services.length - 1];
  22. for (int i = 0; i < services.length; i++) {
  23. if (i != j) {
  24. results[k++] = services[i];
  25. }
  26. }
  27. services = results;
  28. // 将事件发给监听器
  29. support.firePropertyChange("service", service, null);
  30. }
  31. }

下面这些方法是是server对service的管理,server通过这些方法将其下属的service进行初始化,启动,停止,销毁等操作。

  1. /**
  2. * Start nested components ({@link Service}s) and implement the requirements of
  3. * {@link org.apache.catalina.util.LifecycleBase#startInternal()}.
  4. *
  5. * @exception LifecycleException if this component detects a fatal error that prevents this component from being
  6. * used
  7. */
  8. @Override
  9. protected void startInternal() throws LifecycleException {
  10. fireLifecycleEvent(CONFIGURE_START_EVENT, null);
  11. setState(LifecycleState.STARTING);
  12. globalNamingResources.start();
  13. // Start our defined Services
  14. synchronized (servicesLock) {
  15. for (Service service : services) {
  16. service.start();
  17. }
  18. }
  19. }
  20. /**
  21. * Stop nested components ({@link Service}s) and implement the requirements of
  22. * {@link org.apache.catalina.util.LifecycleBase#stopInternal()}.
  23. *
  24. * @exception LifecycleException if this component detects a fatal error that needs to be reported
  25. */
  26. @Override
  27. protected void stopInternal() throws LifecycleException {
  28. setState(LifecycleState.STOPPING);
  29. fireLifecycleEvent(CONFIGURE_STOP_EVENT, null);
  30. // Stop our defined Services
  31. for (Service service : services) {
  32. service.stop();
  33. }
  34. globalNamingResources.stop();
  35. stopAwait();
  36. }
  37. /**
  38. * Invoke a pre-startup initialization. This is used to allow connectors to bind to restricted ports under Unix
  39. * operating environments.
  40. */
  41. @Override
  42. protected void initInternal() throws LifecycleException {
  43. super.initInternal();
  44. // Register global String cache
  45. // Note although the cache is global, if there are multiple Servers
  46. // present in the JVM (may happen when embedding) then the same cache
  47. // will be registered under multiple names
  48. onameStringCache = register(new StringCache(), "type=StringCache");
  49. // Register the MBeanFactory
  50. MBeanFactory factory = new MBeanFactory();
  51. factory.setContainer(this);
  52. onameMBeanFactory = register(factory, "type=MBeanFactory");
  53. // Register the naming resources
  54. globalNamingResources.init();
  55. // Populate the extension validator with JARs from common and shared
  56. // class loaders
  57. if (getCatalina() != null) {
  58. ClassLoader cl = getCatalina().getParentClassLoader();
  59. // Walk the class loader hierarchy. Stop at the system class loader.
  60. // This will add the shared (if present) and common class loaders
  61. while (cl != null && cl != ClassLoader.getSystemClassLoader()) {
  62. if (cl instanceof URLClassLoader) {
  63. URL[] urls = ((URLClassLoader) cl).getURLs();
  64. for (URL url : urls) {
  65. if (url.getProtocol().equals("file")) {
  66. try {
  67. File f = new File(url.toURI());
  68. if (f.isFile() && f.getName().endsWith(".jar")) {
  69. ExtensionValidator.addSystemResource(f);
  70. }
  71. } catch (URISyntaxException | IOException e) {
  72. // Ignore
  73. }
  74. }
  75. }
  76. }
  77. cl = cl.getParent();
  78. }
  79. }
  80. // Initialize our defined Services
  81. for (Service service : services) {
  82. service.init();
  83. }
  84. }
  85. @Override
  86. protected void destroyInternal() throws LifecycleException {
  87. // Destroy our defined Services
  88. for (Service service : services) {
  89. service.destroy();
  90. }
  91. globalNamingResources.destroy();
  92. unregister(onameMBeanFactory);
  93. unregister(onameStringCache);
  94. super.destroyInternal();
  95. }

三、思考点

为什么这里添加服务使用的锁是servicesLock而不是services数组?

  1. /**
  2. * The set of Services associated with this Server.
  3. */
  4. private Service services[] = new Service[0];
  5. private final Object servicesLock = new Object();
  6. @Override
  7. public void addService(Service service) {
  8. service.setServer(this);
  9. //加锁并通过动态数组的方式添加service
  10. synchronized (servicesLock) {
  11. Service results[] = new Service[services.length + 1];
  12. System.arraycopy(services, 0, results, 0, services.length);
  13. results[services.length] = service;
  14. services = results;
  15. if (getState().isAvailable()) {
  16. try {
  17. service.start();
  18. } catch (LifecycleException e) {
  19. // Ignore
  20. }
  21. }
  22. //将添加service的事件发给监听器
  23. support.firePropertyChange("service", null, service);
  24. }
  25. }

我的思考是这样的如果锁住了数组的话,这个数组的读操作就被限制住了,如果别的数组想读的话还要等待,颗粒度太粗,因此使用一个final的对象作为锁锁住代码块,提升代码执行效率。

参考文章:

Server - 简书

本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号