• 深入剖析Tomcat(八) 载入器与打破双亲委派机制的自定义类加载器


    写这篇文章让我头大了好几天,书中描述的内容倒是不多,可能也是那会Tomcat的现状。如今Tomcat发展了好多代,加上springboot的广泛应用,导致现在的类加载的步骤和Tomcat资料中描述的大相径庭。可能也是由于微服务的发展,导致Tomcat中原来可以部署多个应用的特性正在淡化,Tomcat与springboot结合后的启动流程精简了许多。下面我将我了解到的知识介绍一下,有不对的请指出,有新发现我也会继续补充。

    进入正文

    首先,搞清楚两个词语的含义,载入器与类加载器。实现了org.apache.catalina.Loader接口的类为载入器,容器直接持有的是载入器,比如我们前面提到的容器基础类 ContainerBase 中持有一个 Loader 对象的引用。类加载器被载入器持有,作为载入器的一个属性存在。

    载入器

    这是Loader接口的定义

    1. package org.apache.catalina;
    2. import java.beans.PropertyChangeListener;
    3. public interface Loader {
    4. // 持有一个类加载器
    5. public ClassLoader getClassLoader();
    6. // 与此载入器关联的容器对象
    7. public Container getContainer();
    8. public void setContainer(Container container);
    9. // 存储 Host 在创建 Context 时将使用的默认配置
    10. public DefaultContext getDefaultContext();
    11. public void setDefaultContext(DefaultContext defaultContext);
    12. // 配合类加载器使用,设置类加载的流程是否遵循双亲委派机制
    13. public boolean getDelegate();
    14. public void setDelegate(boolean delegate);
    15. public String getInfo();
    16. // 是否支持热部署(动态重新加载类)
    17. public boolean getReloadable();
    18. public void setReloadable(boolean reloadable);
    19. // --------------------------------------------------------- Public Methods
    20. // 设置属性变化监听器
    21. public void addPropertyChangeListener(PropertyChangeListener listener);
    22. public void removePropertyChangeListener(PropertyChangeListener listener);
    23. // 添加一个类加载器的存储库(该载入器持有的类加载器只能去指定的存储库中加载类)
    24. public void addRepository(String repository);
    25. public String[] findRepositories();
    26. // 与此载入器关联的内部库中是否有类文件被修改了?这将会成为是否需要重新加载类(启动热部署)的依据
    27. public boolean modified();
    28. }

    由此接口的定义可以看出:载入器大概有两大功能

    1. 持有一个类加载器,并管理类加载器的一些行为:是否遵循双亲委派机制、包含哪些类库
    2. 拥有热部署的功能,并可设定是否开启。开启后,当class文件或jar包发生更改时,会触发自动重载操作

    Tomcat的载入器通常会与一个Context级别的servlet容器相关联,而Context容器代表的是一个Web应用程序,所以载入器的作用就是加载这个Web应用程序下的类,并支持自动重载(当然也可以关闭自动重载)。

    类加载器

    类加载器其实是jdk中定义的东西,继承了java.lang.ClassLoader的类叫做类加载器。jdk中关于类加载器的实现有很多,Tomcat主要使用URLClassLoader这个类加载器,URLClassLoader可以通过url的形式添加该类加载器的存储库,该类加载器只会去它的存储库中查找并加载类。

    了解过JVM类加载的同学应该都知道双亲委派机制。这里再简单阐述下这个机制。

    双亲委派机制

    jdk定义了三种类加载器

    • 启动类加载器(Bootstrap Class Loader ):负责加载\lib目录中 rt.jar、tools.jar 等包中的基础类
    • 扩展类加载器(Extension Class Loader):负责加载\lib\ext目录中的类
    • 应用程序类加载器(Application Class Loader):也称系统类加载器,system class loader ,它负责加载用户类路径(ClassPath)上的所有类,如果应用程序中没有自定义类加载器的话,一般情况下这个就是程序默认的类加载器。

    用户也可以自定义类加载器,以实现类库的隔离与重载。

    类加载器的双亲委派模型如上图,每个类加载器在收到类加载请求时,都会优先交给它的父类加载器来执行,直到这个加载请求到达启动类加载器,如果父类加载器加载不了,自己才会尝试加载。这种父类优先的模式就形成了如下图所示的这种规则(假如当前场景是应用程序类加载器要加载一个类)

    这种机制保证了JDK中的基础类,如java.lang.Object,java.lang.String等永远只会被启动类加载器加载,不会被用户在项目中编写的同包同名类影响。

    另外,JVM中判断一个Class唯一性的标准为:加载该Class的类加载器+该Class本身。所以双亲委派机制也维护了这一标准,同一个类不会被不同的类加载器加载。

    至于为什么叫双亲委派,我想大概是因为jdk中只定义了三种类加载器,而我们编写的工程类一般使用“应用程序类加载器”,在这个类加载器上面还有两代亲,所以就叫“双亲委派”了。

    Tomcat的自定义类加载器

    Tomcat在诞生之处就实现了一个目标:我不仅是一个Web服务,我还是一个支持部署多个应用的Web服务。Tomcat有一个webapps目录,这个目录下要放的就是我们的项目应用,可以放多个应用,客户端访问时带上应用名就能访问到指定应用。

    这个多应用的支持就对jdk的类加载机制带来了挑战,不同的应用可能会有同包同名的类,或者引用了一个第三方包的不同版本。如果所有应用的类都用系统类加载器来加载的话,那么肯定就会产生冲突了,所以需要一个机制,将不同应用的类加载过程隔离开来,因此,Tomcat自定义了自己的类加载器,来实现自己自定义的类加载逻辑。

    早期的Tomcat的目录结构是下面这样的,(我下载了一个5.0.28版本的Tomcat工程)

    我圈起来的四个包,Tomcat用了四个类加载器来分别加载

    • common目录下的类库可以被Tomcat和所有Web应用共同使用,使用Common类加载器来加载。
    • server目录下的类库可被Tomcat使用,对所有Web应用不可见,使用Catalina类加载器(server类加载器)来加载。
    • shared目录下的类库可被所有Web应用使用,对Tomcat自己不可见,使用 Shared类加载加载。
    • webapps目录下放了1到多个应用目录,每个应用目录的类库仅对该应用自己可见,每个应用使用一个WebApp类加载器实例来加载自己的类。

    所以这四个自定义类加载器结合jdk的三个类加载器就形成了这个关系

    不同的类加载器分别加载各自目录下的类库,也就将各个类库隔离开来了。

    随着Tomcat的发展,在升级到版本6后,它默认的目录结构发生了变化(我下载了一个6.0.0版本的Tomcat工程)

    common、server、shared三个目录没有了,多了一个lib目录,这个lib目录的作用相当于之前common目录的作用,用Common类加载器进行加载。Tomcat这么做说明它也发现了用户实际使用过程中,对server和shared的使用场景很少,所以干脆将它们从默认配置中移除了。如果我升级到了Tomcat高版本,还想用server或shared目录怎么办?那就自己在catalina.properties文件中配置 server.loader与shared.loader两个属性的属性值即可

    由于少了server与shared两个目录,所以默认情况下Tomcat的类加载器的关系又成了这样

    了解了Tomcat的载入器与类加载器的情况,现在来看看它们的代码实现

    载入器的代码实现

    Tomcat提供的载入器实现类为 org.apache.catalina.loader.WebappLoader。

    WebappLoader类中创建了一个自定义类加载器(org.apache.catalina.loader.WebappClassLoader类的实例)。

    WebappLoader类实现了Runnable接口,并开启一个线程来支持类的自动重载。

    WebappLoader类实现了Lifecycle接口,它的start()方法中的主要逻辑为

    • 创建一个类载入器;
    • 设置仓库;
    • 设置类路径;
    • 设置访问权限;
    • 启动一个新线程来支持自动重载。

    接下来分别说一下start方法中的这几件事

    创建一个类载入器

    WebappLoader中有一个loaderClass属性,来存放类加载器的全限定名,默认是org.apache.catalina.loader.WebappClassLoader,也支持修改。

    WebappLoader根据loaderClass来反射创建一个类加载器。

    private String loaderClass = "org.apache.catalina.loader.WebappClassLoader";

    设置仓库

    如果载入器关联的Context容器需要引入额外的类库作为该应用的类库,则将额外的类库设置到WebappLoader的 repositories 属性中(通过addRepository方法),在start()方法中 会首先将repositories中的类库添加到类加载器中,然后调用 setRepositories() 方法将WEB-INF/classes 与 WEB-INF/lib两个类库添加到类加载器中。

    private String[] repositories = new String[0];

    设置类路径

    这是jsp相关的内容,考虑到jsp基本已经不再使用,所以这里不再研究。

    设置访问权限

    访问权限的内容将在第十章进行介绍,这些不做研究。

    启动一个新线程来支持自动重载

    WebappLoader类实现了Runnable接口,在 start 方法中,会启动这个线程,用来不断检查该载入器对应的Context容器中的类(也就是应用程序中的类)是否发生了变更,如果发生了变更则要通知Context进行类重载。

    其中检查类是否发生变更,是调用的类加载器的modified()方法,逻辑由类加载器实现。

    检查到类发生变更后,Tomcat另起了一个线程来调用Context中的reload方法。至于为什么要另起一个线程,我暂时没有理解,如果你知道,还请评论赐教。

    下面是WebappLoader的代码,我省略了一些代码,保留了主要逻辑代码

    1. public class WebappLoader implements Lifecycle, Loader, PropertyChangeListener, Runnable {
    2. // ----------------- 构造方法
    3. public WebappLoader() {
    4. this(null);
    5. }
    6. public WebappLoader(ClassLoader parent) {
    7. super();
    8. this.parentClassLoader = parent;
    9. }
    10. // 热部署线程,巡检的时间间隔
    11. private int checkInterval = 15;
    12. // 类加载器
    13. private WebappClassLoader classLoader = null;
    14. private Container container = null;
    15. protected DefaultContext defaultContext = null;
    16. // 是否遵循双亲委派模型
    17. private boolean delegate = false;
    18. protected LifecycleSupport lifecycle = new LifecycleSupport(this);
    19. // 类加载器的全限定名
    20. private String loaderClass = "org.apache.catalina.loader.WebappClassLoader";
    21. // classLoader的父 类加载器
    22. private ClassLoader parentClassLoader = null;
    23. // 是否支持热重载
    24. private boolean reloadable = false;
    25. // 类加载器关联的类库,这是除了WEB-INF/classes与WEB-INF/lib外的额外类库
    26. private String repositories[] = new String[0];
    27. private boolean started = false;
    28. protected PropertyChangeSupport support = new PropertyChangeSupport(this);
    29. // 热部署巡检线程
    30. private Thread thread = null;
    31. // 巡检线程是否停止了
    32. private boolean threadDone = false;
    33. // 巡检线程的name
    34. private String threadName = "WebappLoader";
    35. // ------------------ Properties
    36. public void setReloadable(boolean reloadable) {
    37. // Process this property change
    38. boolean oldReloadable = this.reloadable;
    39. this.reloadable = reloadable;
    40. support.firePropertyChange("reloadable", new Boolean(oldReloadable), new Boolean(this.reloadable));
    41. // Start or stop our background thread if required
    42. if (!started) return;
    43. if (!oldReloadable && this.reloadable) threadStart();
    44. else if (oldReloadable && !this.reloadable) threadStop();
    45. }
    46. // ------------------ Public Methods
    47. /**
    48. * Has the internal repository associated with this Loader been modified,
    49. * such that the loaded classes should be reloaded?
    50. */
    51. public boolean modified() {
    52. return (classLoader.modified());
    53. }
    54. // ------------------ Lifecycle Methods
    55. public void start() throws LifecycleException {
    56. if (started) {
    57. throw new LifecycleException(sm.getString("webappLoader.alreadyStarted"));
    58. }
    59. lifecycle.fireLifecycleEvent(START_EVENT, null);
    60. started = true;
    61. if (container.getResources() == null) {
    62. return;
    63. }
    64. try {
    65. // 创建类加载器
    66. classLoader = createClassLoader();
    67. classLoader.setResources(container.getResources());
    68. classLoader.setDebug(this.debug);
    69. classLoader.setDelegate(this.delegate);
    70. // 如果载入器额外设置了类库,则将这些类库添加到类加载器的类库中
    71. for (int i = 0; i < repositories.length; i++) {
    72. classLoader.addRepository(repositories[i]);
    73. }
    74. // 设置仓库,WEB_INF/classes 与 WEB_INF/lib 两个目录
    75. setRepositories();
    76. // 设置类路径,与JSP相关,不再研究
    77. setClassPath();
    78. // 设置访问权限,这块内容后面章节再介绍
    79. setPermissions();
    80. if (classLoader instanceof Lifecycle) {
    81. ((Lifecycle) classLoader).start();
    82. }
    83. // Binding the Webapp class loader to the directory context
    84. DirContextURLStreamHandler.bind((ClassLoader) classLoader, this.container.getResources());
    85. } catch (Throwable t) {
    86. throw new LifecycleException("start: ", t);
    87. }
    88. // 验证所有必需的包都是实际可用的,这个方法这里暂不研究
    89. validatePackages();
    90. // 如果支持重载的话,开启一个守护线程来巡检,在线程内完成重载的触发流程
    91. if (reloadable) {
    92. log(sm.getString("webappLoader.reloading"));
    93. try {
    94. threadStart();
    95. } catch (IllegalStateException e) {
    96. throw new LifecycleException(e);
    97. }
    98. }
    99. }
    100. public void stop() throws LifecycleException {
    101. // Validate and update our current component state
    102. if (!started) throw new LifecycleException(sm.getString("webappLoader.notStarted"));
    103. lifecycle.fireLifecycleEvent(STOP_EVENT, null);
    104. started = false;
    105. // Stop our background thread if we are reloadable
    106. if (reloadable) threadStop();
    107. // Remove context attributes as appropriate
    108. if (container instanceof Context) {
    109. ServletContext servletContext = ((Context) container).getServletContext();
    110. servletContext.removeAttribute(Globals.CLASS_PATH_ATTR);
    111. }
    112. // Throw away our current class loader
    113. if (classLoader instanceof Lifecycle) ((Lifecycle) classLoader).stop();
    114. DirContextURLStreamHandler.unbind((ClassLoader) classLoader);
    115. classLoader = null;
    116. }
    117. // ------------------------------------------------------- Private Methods
    118. /**
    119. * 创建一个类加载器
    120. */
    121. private WebappClassLoader createClassLoader() throws Exception {
    122. Class clazz = Class.forName(loaderClass);
    123. WebappClassLoader classLoader = null;
    124. // 根据 parentClassLoader 有没有值来使用 WebappClassLoader 的不同构造函数
    125. if (parentClassLoader == null) {
    126. classLoader = (WebappClassLoader) clazz.newInstance();
    127. } else {
    128. Class[] argTypes = {ClassLoader.class};
    129. Object[] args = {parentClassLoader};
    130. Constructor constr = clazz.getConstructor(argTypes);
    131. classLoader = (WebappClassLoader) constr.newInstance(args);
    132. }
    133. return classLoader;
    134. }
    135. /**
    136. * 基于关联的Context,为我们的类加载器配置类库。主要是 WEB-INF/classes 和 WEB-INF/lib 两个目录
    137. */
    138. private void setRepositories() {
    139. if (!(container instanceof Context)) return;
    140. ServletContext servletContext = ((Context) container).getServletContext();
    141. if (servletContext == null) return;
    142. // Loading the work directory
    143. File workDir = (File) servletContext.getAttribute(Globals.WORK_DIR_ATTR);
    144. if (workDir == null) return;
    145. log(sm.getString("webappLoader.deploy", workDir.getAbsolutePath()));
    146. DirContext resources = container.getResources();
    147. // Setting up the class repository (/WEB-INF/classes), if it exists
    148. String classesPath = "/WEB-INF/classes";
    149. DirContext classes = null;
    150. try {
    151. Object object = resources.lookup(classesPath);
    152. if (object instanceof DirContext) {
    153. classes = (DirContext) object;
    154. }
    155. } catch (NamingException e) {
    156. // Silent catch: it's valid that no /WEB-INF/classes collection
    157. // exists
    158. }
    159. if (classes != null) {
    160. File classRepository = null;
    161. String absoluteClassesPath = servletContext.getRealPath(classesPath);
    162. if (absoluteClassesPath != null) {
    163. classRepository = new File(absoluteClassesPath);
    164. } else {
    165. classRepository = new File(workDir, classesPath);
    166. classRepository.mkdirs();
    167. copyDir(classes, classRepository);
    168. }
    169. log(sm.getString("webappLoader.classDeploy", classesPath, classRepository.getAbsolutePath()));
    170. // Adding the repository to the class loader
    171. classLoader.addRepository(classesPath + "/", classRepository);
    172. }
    173. // Setting up the JAR repository (/WEB-INF/lib), if it exists
    174. String libPath = "/WEB-INF/lib";
    175. classLoader.setJarPath(libPath);
    176. DirContext libDir = null;
    177. // Looking up directory /WEB-INF/lib in the context
    178. try {
    179. Object object = resources.lookup(libPath);
    180. if (object instanceof DirContext) libDir = (DirContext) object;
    181. } catch (NamingException e) {
    182. // Silent catch: it's valid that no /WEB-INF/lib collection
    183. // exists
    184. }
    185. if (libDir != null) {
    186. boolean copyJars = false;
    187. String absoluteLibPath = servletContext.getRealPath(libPath);
    188. File destDir = null;
    189. if (absoluteLibPath != null) {
    190. destDir = new File(absoluteLibPath);
    191. } else {
    192. copyJars = true;
    193. destDir = new File(workDir, libPath);
    194. destDir.mkdirs();
    195. }
    196. // Looking up directory /WEB-INF/lib in the context
    197. try {
    198. NamingEnumeration myEnum = resources.listBindings(libPath);
    199. while (myEnum.hasMoreElements()) {
    200. Binding binding = (Binding) myEnum.nextElement();
    201. String filename = libPath + "/" + binding.getName();
    202. if (!filename.endsWith(".jar")) continue;
    203. // Copy JAR in the work directory, always (the JAR file
    204. // would get locked otherwise, which would make it
    205. // impossible to update it or remove it at runtime)
    206. File destFile = new File(destDir, binding.getName());
    207. log(sm.getString("webappLoader.jarDeploy", filename, destFile.getAbsolutePath()));
    208. Resource jarResource = (Resource) binding.getObject();
    209. if (copyJars) {
    210. if (!copy(jarResource.streamContent(), new FileOutputStream(destFile))) continue;
    211. }
    212. JarFile jarFile = new JarFile(destFile);
    213. classLoader.addJar(filename, jarFile, destFile);
    214. }
    215. } catch (NamingException e) {
    216. // Silent catch: it's valid that no /WEB-INF/lib directory
    217. // exists
    218. } catch (IOException e) {
    219. e.printStackTrace();
    220. }
    221. }
    222. }
    223. // 开启一个巡检线程
    224. private void threadStart() {
    225. // Has the background thread already been started?
    226. if (thread != null) return;
    227. // Validate our current state
    228. if (!reloadable) throw new IllegalStateException(sm.getString("webappLoader.notReloadable"));
    229. if (!(container instanceof Context)) throw new IllegalStateException(sm.getString("webappLoader.notContext"));
    230. // Start the background thread
    231. threadDone = false;
    232. threadName = "WebappLoader[" + container.getName() + "]";
    233. thread = new Thread(this, threadName);
    234. thread.setDaemon(true);
    235. thread.start();
    236. }
    237. // 让当前线程睡一会
    238. private void threadSleep() {
    239. try {
    240. Thread.sleep(checkInterval * 1000L);
    241. } catch (InterruptedException e) {
    242. ;
    243. }
    244. }
    245. // 停止巡检线程
    246. private void threadStop() {
    247. if (thread == null) return;
    248. threadDone = true;
    249. thread.interrupt();
    250. try {
    251. thread.join();
    252. } catch (InterruptedException e) {
    253. ;
    254. }
    255. thread = null;
    256. }
    257. // 巡检线程的run方法
    258. public void run() {
    259. // 循环检查,直到 threadDone 为 true
    260. while (!threadDone) {
    261. // 睡一会再检查
    262. threadSleep();
    263. if (!started) break;
    264. try {
    265. // 检查类是否被更改过
    266. if (!classLoader.modified()) {
    267. continue;
    268. }
    269. } catch (Exception e) {
    270. log(sm.getString("webappLoader.failModifiedCheck"), e);
    271. continue;
    272. }
    273. // 检查到类被更改过,通知Context去重载类
    274. notifyContext();
    275. break;
    276. }
    277. }
    278. /**
    279. * 另外开启一个线程来通知Context容器需要进行类重载了
    280. */
    281. private void notifyContext() {
    282. WebappContextNotifier notifier = new WebappContextNotifier();
    283. (new Thread(notifier)).start();
    284. }
    285. // -------------------- WebappContextNotifier 内部类
    286. /**
    287. * 私有线程类来通知关联Context,需要重新加载类了。
    288. */
    289. protected class WebappContextNotifier implements Runnable {
    290. public void run() {
    291. // 类重载的逻辑实际在Context容器类中
    292. ((Context) container).reload();
    293. }
    294. }
    295. }

    自定义类加载器的代码实现

    Tomcat为Web应用程序做的类加载器为org.apache.catalina.loader.WebappClassLoader类的实例,WebappClassLoader继承自URLClassLoader。

    WebappClassLoader中主要是对类加载的逻辑做了自定义,用来隔离各个Web应用的类库。同时它也做了一些缓存,来提升类加载的效率。

    考虑到安全性,WebappClassLoader 类不允许载入指定的某些类,这些类的名字存储在一个字符串数组变量triggers 中,当前只有一个元素 

    此外,某些特殊的包及其子包下的类也是不允许WebApp类加载器直接加载的,需要先委托父类加载器去加载。

    每个由 WebappClassLoader载入的类(无论是在WEB-INF/classes 目录下还是从某个JAR文件内作为类文件部署 ), 都视为“资源”。资源是 org.apache.catalina.loader.ResourceEntry类的实 例 。ResourceEntry 实例会保存其所代表的class 文件的字节流、最后一次修改日期、Manifest 信息(如果资源来自与一个JAR 文件的话)等。

    为了达到更好的新能,WebappClassLoader会缓存已经加载过的类,放到 resourceEntries 这个map中。

    protected HashMap resourceEntries = new HashMap<>();

    另外,如果WebappClassLoader在尝试加载某类时,没有找到此类并报了ClassNotFoundException,那么WebappClassLoader也会将这个不存在的类记录下来,下次再需要加载时直接抛异常就行。

    protected HashMap notFoundResources = new HashMap<>();

    本章应用程序中没有定义common类加载类,所以本章代码中类加载器的结构如下

    WebappClassLoader中有两个类加载器属性

    parent是它的父类加载器,正常来说这个值应该是common类加载器,但是我们本次代码并没有创建common类加载器,所以parent属性为null。

    sytem就是系统类加载器,也就是应用程序类加载器。

    WebappClassLoader类重写了loadClass方法,自定义的类加载逻辑如下图

    WebappClassLoader在加载类时会首先委托应用程序类加载器去加载,应用程序类加载器能加载哪些类呢?

    应用程序类加载器默认加载以下目录和文件中的类:

    1.通过 -classpath 或 -cp 参数指定的路径:
    当启动Java应用程序时,可以使用 -classpath 或 -cp 参数来指定一个或多个目录和JAR文件,作为类的搜索路径。
    例如:java -classpath /path/to/classes:/path/to/lib/some-library.jar com.example.Main
    2.环境变量 CLASSPATH 指定的路径:
    如果没有使用 -classpath 或 -cp 参数,系统类加载器会使用环境变量 CLASSPATH 中指定的路径。
    例如,CLASSPATH=/path/to/classes:/path/to/lib/some-library.jar
    3.当前工作目录:
    如果 CLASSPATH 没有指定,系统类加载器会默认包含当前工作目录(.),即应用程序启动时的工作目录。

    在通过WebappClassLoader加载的一个应用程序中的类中,如果依赖了其他类,这些其他类也会通过WebappClassLoader来加载,后面我会通过一个MyObject的例子来验证。

    WebappClassLoader 中含有 modified() 方法,用来判断该类加载器对应的类库中有没有class文件或jar包被修改了。这个方法会被WebappLoader中的热加载巡检线程不断调用。

    下面是WebappClassLoader的部分代码,完整代码请看源码

    1. public class WebappClassLoader extends URLClassLoader implements Reloader, Lifecycle {
    2. private static final String[] triggers = {"javax.servlet.Servlet" // Servlet API
    3. };
    4. private static final String[] packageTriggers = {"javax", // Java extensions
    5. "org.xml.sax", // SAX 1 & 2
    6. "org.w3c.dom", // DOM 1 & 2
    7. "org.apache.xerces", // Xerces 1 & 2
    8. "org.apache.xalan" // Xalan
    9. };
    10. public WebappClassLoader() {
    11. super(new URL[0]);
    12. this.parent = getParent();
    13. system = getSystemClassLoader();
    14. }
    15. public WebappClassLoader(ClassLoader parent) {
    16. super(new URL[0], parent);
    17. this.parent = getParent();
    18. system = getSystemClassLoader();
    19. }
    20. // 缓存已经加载过的类
    21. protected HashMap resourceEntries = new HashMap<>();
    22. // 缓存找不到的那些类的类名
    23. protected HashMap notFoundResources = new HashMap<>();
    24. // 是否遵循双亲委派模型
    25. protected boolean delegate = false;
    26. // 该类加载器的类库
    27. protected String[] repositories = new String[0];
    28. // 该类加载器的jar包类库
    29. protected JarFile[] jarFiles = new JarFile[0];
    30. // jar包名字的集合
    31. protected String[] jarNames = new String[0];
    32. // jar包类库中各jar包的最后修改日期
    33. protected long[] lastModifiedDates = new long[0];
    34. // modify方法需要检查的所有资源路径
    35. protected String[] paths = new String[0];
    36. // 父 类加载器
    37. private ClassLoader parent = null;
    38. // 系统类加载器
    39. private ClassLoader system = null;
    40. public Class loadClass(String name) throws ClassNotFoundException {
    41. return loadClass(name, false);
    42. }
    43. public Class loadClass(String name, boolean resolve) throws ClassNotFoundException {
    44. Class clazz = null;
    45. // Don't load classes if class loader is stopped
    46. if (!started) {
    47. log("Lifecycle error : CL stopped");
    48. throw new ClassNotFoundException(name);
    49. }
    50. // (0) 检查该类加载器的缓存中存在
    51. clazz = findLoadedClass0(name);
    52. if (clazz != null) {
    53. if (resolve) {
    54. resolveClass(clazz);
    55. }
    56. return clazz;
    57. }
    58. // (0.1) 检查JVM提供的类加载缓存中是否存在
    59. clazz = findLoadedClass(name);
    60. if (clazz != null) {
    61. if (resolve) {
    62. resolveClass(clazz);
    63. }
    64. return clazz;
    65. }
    66. // (0.2) 尝试使用系统类加载器进行加载,方式应用程序中类覆盖 J2SE 中的类
    67. try {
    68. clazz = system.loadClass(name);
    69. if (clazz != null) {
    70. if (resolve) resolveClass(clazz);
    71. return (clazz);
    72. }
    73. } catch (ClassNotFoundException e) {
    74. // Ignore
    75. }
    76. // (0.5) Permission to access this class when using a SecurityManager
    77. if (securityManager != null) {
    78. int i = name.lastIndexOf('.');
    79. if (i >= 0) {
    80. try {
    81. securityManager.checkPackageAccess(name.substring(0, i));
    82. } catch (SecurityException se) {
    83. String error = "Security Violation, attempt to use " + "Restricted Class: " + name;
    84. System.out.println(error);
    85. se.printStackTrace();
    86. log(error);
    87. throw new ClassNotFoundException(error);
    88. }
    89. }
    90. }
    91. boolean delegateLoad = delegate || filter(name);
    92. // (1) 如果遵循双亲委派机制的话,要先交给父类加载器去加载
    93. if (delegateLoad) {
    94. ClassLoader loader = parent;
    95. if (loader == null) loader = system;
    96. try {
    97. clazz = loader.loadClass(name);
    98. if (clazz != null) {
    99. if (debug >= 3) log(" Loading class from parent");
    100. if (resolve) resolveClass(clazz);
    101. return (clazz);
    102. }
    103. } catch (ClassNotFoundException e) {
    104. ;
    105. }
    106. }
    107. // (2) WebappClassLoader自己加载,从自己的类库中加载
    108. try {
    109. clazz = findClass(name);
    110. if (clazz != null) {
    111. if (debug >= 3) log(" Loading class from local repository");
    112. if (resolve) resolveClass(clazz);
    113. return (clazz);
    114. }
    115. } catch (ClassNotFoundException e) {
    116. ;
    117. }
    118. // (3) 强制使用父类加载器进行加载
    119. if (!delegateLoad) {
    120. if (debug >= 3) log(" Delegating to parent classloader");
    121. ClassLoader loader = parent;
    122. if (loader == null) loader = system;
    123. try {
    124. clazz = loader.loadClass(name);
    125. if (clazz != null) {
    126. if (debug >= 3) log(" Loading class from parent");
    127. if (resolve) resolveClass(clazz);
    128. return (clazz);
    129. }
    130. } catch (ClassNotFoundException e) {
    131. ;
    132. }
    133. }
    134. // This class was not found
    135. throw new ClassNotFoundException(name);
    136. }
    137. public Class findClass(String name) throws ClassNotFoundException {
    138. if (debug >= 3) {
    139. log(" findClass(" + name + ")");
    140. }
    141. // (1) Permission to define this class when using a SecurityManager
    142. if (securityManager != null) {
    143. int i = name.lastIndexOf('.');
    144. if (i >= 0) {
    145. try {
    146. if (debug >= 4) log(" securityManager.checkPackageDefinition");
    147. securityManager.checkPackageDefinition(name.substring(0, i));
    148. } catch (Exception se) {
    149. if (debug >= 4) log(" -->Exception-->ClassNotFoundException", se);
    150. throw new ClassNotFoundException(name);
    151. }
    152. }
    153. }
    154. // Ask our superclass to locate this class, if possible
    155. // (throws ClassNotFoundException if it is not found)
    156. Class clazz = null;
    157. try {
    158. if (debug >= 4) log(" findClassInternal(" + name + ")");
    159. try {
    160. clazz = findClassInternal(name);
    161. } catch (ClassNotFoundException cnfe) {
    162. if (!hasExternalRepositories) {
    163. throw cnfe;
    164. }
    165. } catch (AccessControlException ace) {
    166. ace.printStackTrace();
    167. throw new ClassNotFoundException(name);
    168. } catch (RuntimeException e) {
    169. if (debug >= 4) log(" -->RuntimeException Rethrown", e);
    170. throw e;
    171. }
    172. if ((clazz == null) && hasExternalRepositories) {
    173. try {
    174. clazz = super.findClass(name);
    175. } catch (AccessControlException ace) {
    176. throw new ClassNotFoundException(name);
    177. } catch (RuntimeException e) {
    178. if (debug >= 4) log(" -->RuntimeException Rethrown", e);
    179. throw e;
    180. }
    181. }
    182. if (clazz == null) {
    183. if (debug >= 3) log(" --> Returning ClassNotFoundException");
    184. throw new ClassNotFoundException(name);
    185. }
    186. } catch (ClassNotFoundException e) {
    187. if (debug >= 3) log(" --> Passing on ClassNotFoundException", e);
    188. throw e;
    189. }
    190. // Return the class we have located
    191. if (debug >= 4) log(" Returning class " + clazz);
    192. if ((debug >= 4) && (clazz != null)) log(" Loaded by " + clazz.getClassLoader());
    193. return (clazz);
    194. }
    195. /**
    196. * 添加一个类库到类加载器的类库集合中,该类加载器将加载这些类库中的类。
    197. * 这个方法只接受一个参数,即类库的路径名。它的作用是向 WebappClassLoader 中添加一个新的类库路径;
    198. * 这个方法假设类库路径指向的是一个有效的 URL,并且不进行文件存在性检查。
    199. */
    200. public void addRepository(String repository) {
    201. // 忽略标准库,他们已经被其他方法加载过了
    202. if (repository.startsWith("/WEB-INF/lib") || repository.startsWith("/WEB-INF/classes")) {
    203. return;
    204. }
    205. // Add this repository to our underlying class loader
    206. try {
    207. URL url = new URL(repository);
    208. super.addURL(url);
    209. hasExternalRepositories = true;
    210. } catch (MalformedURLException e) {
    211. throw new IllegalArgumentException(e.toString());
    212. }
    213. }
    214. /**
    215. * 同addRepository(String repository),第二个参数file是类库的绝对路径file
    216. * 这个方法接受两个参数,第一个参数是类库的路径名,第二个参数是表示类库文件的 File对象。与第一个方法不同的是,这个方法会将类库路径名和对应的文件对象一一对应地添加到内部的数组中。这种方式更为灵活,因为它可以将路径名和文件对象关联起来,便于后续的管理和使用。
    217. */
    218. synchronized void addRepository(String repository, File file) {
    219. if (repository == null) return;
    220. int i;
    221. // Add this repository to our internal list
    222. String[] result = new String[repositories.length + 1];
    223. for (i = 0; i < repositories.length; i++) {
    224. result[i] = repositories[i];
    225. }
    226. result[repositories.length] = repository;
    227. repositories = result;
    228. // Add the file to the list
    229. File[] result2 = new File[files.length + 1];
    230. for (i = 0; i < files.length; i++) {
    231. result2[i] = files[i];
    232. }
    233. result2[files.length] = file;
    234. files = result2;
    235. }
    236. /**
    237. * 将一个jar包加到类库中
    238. */
    239. synchronized void addJar(String jar, JarFile jarFile, File file) throws IOException {
    240. if (jar == null) return;
    241. if (jarFile == null) return;
    242. if (file == null) return;
    243. int i;
    244. if ((jarPath != null) && (jar.startsWith(jarPath))) {
    245. String jarName = jar.substring(jarPath.length());
    246. while (jarName.startsWith("/")) jarName = jarName.substring(1);
    247. String[] result = new String[jarNames.length + 1];
    248. for (i = 0; i < jarNames.length; i++) {
    249. result[i] = jarNames[i];
    250. }
    251. result[jarNames.length] = jarName;
    252. jarNames = result;
    253. }
    254. try {
    255. // Register the JAR for tracking
    256. long lastModified = ((ResourceAttributes) resources.getAttributes(jar)).getLastModified();
    257. String[] result = new String[paths.length + 1];
    258. for (i = 0; i < paths.length; i++) {
    259. result[i] = paths[i];
    260. }
    261. result[paths.length] = jar;
    262. paths = result;
    263. long[] result3 = new long[lastModifiedDates.length + 1];
    264. for (i = 0; i < lastModifiedDates.length; i++) {
    265. result3[i] = lastModifiedDates[i];
    266. }
    267. result3[lastModifiedDates.length] = lastModified;
    268. lastModifiedDates = result3;
    269. } catch (NamingException e) {
    270. // Ignore
    271. }
    272. // If the JAR currently contains invalid classes, don't actually use it
    273. // for classloading
    274. if (!validateJarFile(file)) return;
    275. JarFile[] result2 = new JarFile[jarFiles.length + 1];
    276. for (i = 0; i < jarFiles.length; i++) {
    277. result2[i] = jarFiles[i];
    278. }
    279. result2[jarFiles.length] = jarFile;
    280. jarFiles = result2;
    281. // Add the file to the list
    282. File[] result4 = new File[jarRealFiles.length + 1];
    283. for (i = 0; i < jarRealFiles.length; i++) {
    284. result4[i] = jarRealFiles[i];
    285. }
    286. result4[jarRealFiles.length] = file;
    287. jarRealFiles = result4;
    288. // Load manifest
    289. Manifest manifest = jarFile.getManifest();
    290. if (manifest != null) {
    291. Iterator extensions = Extension.getAvailable(manifest).iterator();
    292. while (extensions.hasNext()) {
    293. available.add(extensions.next());
    294. }
    295. extensions = Extension.getRequired(manifest).iterator();
    296. while (extensions.hasNext()) {
    297. required.add(extensions.next());
    298. }
    299. }
    300. }
    301. /**
    302. * 是否有类文件或jar包被修改了?
    303. */
    304. public boolean modified() {
    305. // Checking for modified loaded resources
    306. int length = paths.length;
    307. // A rare race condition can occur in the updates of the two arrays
    308. // It's totally ok if the latest class added is not checked (it will
    309. // be checked the next time
    310. int length2 = lastModifiedDates.length;
    311. if (length > length2) length = length2;
    312. for (int i = 0; i < length; i++) {
    313. try {
    314. long lastModified = ((ResourceAttributes) resources.getAttributes(paths[i])).getLastModified();
    315. if (lastModified != lastModifiedDates[i]) {
    316. log(" Resource '" + paths[i] + "' was modified; Date is now: " + new java.util.Date(lastModified) + " Was: " + new java.util.Date(lastModifiedDates[i]));
    317. return (true);
    318. }
    319. } catch (NamingException e) {
    320. log(" Resource '" + paths[i] + "' is missing");
    321. return (true);
    322. }
    323. }
    324. length = jarNames.length;
    325. // Check if JARs have been added or removed
    326. if (getJarPath() != null) {
    327. try {
    328. NamingEnumeration myEnum = resources.listBindings(getJarPath());
    329. int i = 0;
    330. while (myEnum.hasMoreElements() && (i < length)) {
    331. NameClassPair ncPair = (NameClassPair) myEnum.nextElement();
    332. String name = ncPair.getName();
    333. // Ignore non JARs present in the lib folder
    334. if (!name.endsWith(".jar")) continue;
    335. if (!name.equals(jarNames[i])) {
    336. // Missing JAR
    337. log(" Additional JARs have been added : '" + name + "'");
    338. return (true);
    339. }
    340. i++;
    341. }
    342. if (myEnum.hasMoreElements()) {
    343. while (myEnum.hasMoreElements()) {
    344. NameClassPair ncPair = (NameClassPair) myEnum.nextElement();
    345. String name = ncPair.getName();
    346. // Additional non-JAR files are allowed
    347. if (name.endsWith(".jar")) {
    348. // There was more JARs
    349. log(" Additional JARs have been added");
    350. return (true);
    351. }
    352. }
    353. } else if (i < jarNames.length) {
    354. // There was less JARs
    355. log(" Additional JARs have been added");
    356. return (true);
    357. }
    358. } catch (NamingException e) {
    359. if (debug > 2) log(" Failed tracking modifications of '" + getJarPath() + "'");
    360. } catch (ClassCastException e) {
    361. log(" Failed tracking modifications of '" + getJarPath() + "' : " + e.getMessage());
    362. }
    363. }
    364. // No classes have been modified
    365. return (false);
    366. }
    367. }

    StandardContext类

    StandardContext类的具体内容将放到第十二章来讲,这里仅列出它的 reload() 方法,即类重载的方法。看上去其实就是一个Context容器的重启过程:先将容器实例及其相关组件实例stop掉,然后在start起来。

    1. public synchronized void reload() {
    2. // Validate our current component state
    3. if (!started) throw new IllegalStateException(sm.getString("containerBase.notStarted", logName()));
    4. // Make sure reloading is enabled
    5. // if (!reloadable)
    6. // throw new IllegalStateException
    7. // (sm.getString("standardContext.notReloadable"));
    8. log(sm.getString("standardContext.reloadingStarted"));
    9. // Stop accepting requests temporarily
    10. setPaused(true);
    11. // Binding thread
    12. ClassLoader oldCCL = bindThread();
    13. // Shut down our session manager
    14. if ((manager != null) && (manager instanceof Lifecycle)) {
    15. try {
    16. ((Lifecycle) manager).stop();
    17. } catch (LifecycleException e) {
    18. log(sm.getString("standardContext.stoppingManager"), e);
    19. }
    20. }
    21. // Shut down the current version of all active servlets
    22. Container children[] = findChildren();
    23. for (int i = 0; i < children.length; i++) {
    24. Wrapper wrapper = (Wrapper) children[i];
    25. if (wrapper instanceof Lifecycle) {
    26. try {
    27. ((Lifecycle) wrapper).stop();
    28. } catch (LifecycleException e) {
    29. log(sm.getString("standardContext.stoppingWrapper", wrapper.getName()), e);
    30. }
    31. }
    32. }
    33. // Shut down application event listeners
    34. listenerStop();
    35. // Clear all application-originated servlet context attributes
    36. if (context != null) context.clearAttributes();
    37. // Shut down filters
    38. filterStop();
    39. if (isUseNaming()) {
    40. // Start
    41. namingContextListener.lifecycleEvent(new LifecycleEvent(this, Lifecycle.STOP_EVENT));
    42. }
    43. // Binding thread
    44. unbindThread(oldCCL);
    45. // Shut down our application class loader
    46. if ((loader != null) && (loader instanceof Lifecycle)) {
    47. try {
    48. ((Lifecycle) loader).stop();
    49. } catch (LifecycleException e) {
    50. log(sm.getString("standardContext.stoppingLoader"), e);
    51. }
    52. }
    53. // Binding thread
    54. oldCCL = bindThread();
    55. // Restart our application class loader
    56. if ((loader != null) && (loader instanceof Lifecycle)) {
    57. try {
    58. ((Lifecycle) loader).start();
    59. } catch (LifecycleException e) {
    60. log(sm.getString("standardContext.startingLoader"), e);
    61. }
    62. }
    63. // Binding thread
    64. unbindThread(oldCCL);
    65. // Create and register the associated naming context, if internal
    66. // naming is used
    67. boolean ok = true;
    68. if (isUseNaming()) {
    69. // Start
    70. namingContextListener.lifecycleEvent(new LifecycleEvent(this, Lifecycle.START_EVENT));
    71. }
    72. // Binding thread
    73. oldCCL = bindThread();
    74. // Restart our application event listeners and filters
    75. if (ok) {
    76. if (!listenerStart()) {
    77. log(sm.getString("standardContext.listenerStartFailed"));
    78. ok = false;
    79. }
    80. }
    81. if (ok) {
    82. if (!filterStart()) {
    83. log(sm.getString("standardContext.filterStartFailed"));
    84. ok = false;
    85. }
    86. }
    87. // Restore the "Welcome Files" and "Resources" context attributes
    88. postResources();
    89. postWelcomeFiles();
    90. // Restart our currently defined servlets
    91. for (int i = 0; i < children.length; i++) {
    92. if (!ok) break;
    93. Wrapper wrapper = (Wrapper) children[i];
    94. if (wrapper instanceof Lifecycle) {
    95. try {
    96. ((Lifecycle) wrapper).start();
    97. } catch (LifecycleException e) {
    98. log(sm.getString("standardContext.startingWrapper", wrapper.getName()), e);
    99. ok = false;
    100. }
    101. }
    102. }
    103. // Reinitialize all load on startup servlets
    104. loadOnStartup(children);
    105. // Restart our session manager (AFTER naming context recreated/bound)
    106. if ((manager != null) && (manager instanceof Lifecycle)) {
    107. try {
    108. ((Lifecycle) manager).start();
    109. } catch (LifecycleException e) {
    110. log(sm.getString("standardContext.startingManager"), e);
    111. }
    112. }
    113. // Unbinding thread
    114. unbindThread(oldCCL);
    115. // Start accepting requests again
    116. if (ok) {
    117. log(sm.getString("standardContext.reloadingCompleted"));
    118. } else {
    119. setAvailable(false);
    120. log(sm.getString("standardContext.reloadingFailed"));
    121. }
    122. setPaused(false);
    123. // Notify our interested LifecycleListeners
    124. lifecycle.fireLifecycleEvent(Context.RELOAD_EVENT, null);
    125. }

    Web应用程序

    下面来构建两个应用程序,作为Tomcat中存放的应用程序,他们分别由不同的载入器实例来加载。我们仍然使用前面章节用到的ModernServlet与PrimitiveServlet来作为应用程序的servlet。至于lib包下的simple-project-1.0-SNAPSHOT.jar则是只提供了一个MyObject类

     

    MyObject类中打印了加载该类的类加载器,并提供了一个print方法

    1. public class MyObject {
    2. public MyObject() {
    3. ClassLoader classLoader = this.getClass().getClassLoader();
    4. System.out.println("=======MyObject's classLoader is: "+classLoader.toString());
    5. }
    6. public void print() {
    7. System.out.println("=======MyObject print [AAAAAA]");
    8. }
    9. }

    ModernServlet的doGet方法末尾使用了MyObject类,创建了一个MyObject对象并调用其print方法。

    1. public class ModernServlet extends HttpServlet {
    2. public void init(ServletConfig config) {
    3. System.out.println("ModernServlet -- init");
    4. }
    5. public void doGet(HttpServletRequest request,
    6. HttpServletResponse response)
    7. throws ServletException, IOException {
    8. response.setContentType("text/html");
    9. PrintWriter out = response.getWriter();
    10. //先输出HTTP的头部信息
    11. String msg = "HTTP/1.1 200 OK\r\n" +
    12. "Content-Type: text/html\r\n" +
    13. "Transfer-Encoding: chunked\r\n" +
    14. "\r\n";
    15. out.print(msg);
    16. StringBuilder builder = new StringBuilder();
    17. //再输出HTTP的消息体
    18. builder.append("");
    19. builder.append("");
    20. builder.append("Modern Servlet");
    21. builder.append("");
    22. builder.append("");
    23. builder.append("

      Headers

      "
      );
    24. Enumeration headers = request.getHeaderNames();
    25. while (headers.hasMoreElements()) {
    26. String header = (String) headers.nextElement();
    27. builder.append("
      "
      + header + " : " + request.getHeader(header));
    28. }
    29. builder.append("

      Method

      "
      );
    30. builder.append("
      "
      + request.getMethod());
    31. builder.append("

      Parameters

      "
      );
    32. Enumeration parameters = request.getParameterNames();
    33. while (parameters.hasMoreElements()) {
    34. String parameter = (String) parameters.nextElement();
    35. builder.append("
      "
      + parameter + " : " + request.getParameter(parameter));
    36. }
    37. builder.append("

      Query String

      "
      );
    38. builder.append("
      "
      + request.getQueryString());
    39. builder.append("

      Request URI

      "
      );
    40. builder.append("
      "
      + request.getRequestURI());
    41. builder.append("");
    42. builder.append("");
    43. // 这里是与原书中代码不一样的地方,原代码没有加chunked块的长度,浏览器不能正常解析
    44. out.print(Integer.toHexString(builder.length()) + "\r\n");
    45. out.print(builder.toString() + "\r\n");
    46. out.print("0\r\n\r\n");
    47. out.flush();
    48. out.close();
    49. MyObject myObject = new MyObject();
    50. myObject.print();
    51. }
    52. }

    这里我加入MyObject这个类,是有两种用途

    1. 检测WebappClassLoader是否能加载 WEB-INF/lib 包下的jar包中的类。
    2. 在ModernServlet执行doGet方法时,发现其依赖MyObject,测试MyObject类是否是和ModernServlet用的同一个类加载实例来加载的。

    另外我构建了两个应用程序 myApp与myApp2,使用了同一套代码,我们可以来检查下,这两个应用程序下相同的类是否是由不同的WebappClassLoader实例来加载的。

    我写了一段检测不同类的类加载器的代码,放在了Wrapper容器的基础阀SimpleWrapperValve中,在Wrapper实例获取到对应的servlet后,打印了一下加载该servlet的类加载器;这里还打印了一下HttpServlet类的类加载器,HttpServlet类在项目最外层的lib包中,是我设置的整个项目的lib依赖,这个lib包理应会被加入到应用程序类加载器的类库中,所以HttpServlet类的类加载器应该是 sun.misc.Launcher.AppClassLoader

    1. public class SimpleWrapperValve implements Valve, Contained {
    2. protected Container container;
    3. public void invoke(Request request, Response response, ValveContext valveContext)
    4. throws IOException, ServletException {
    5. SimpleWrapper wrapper = (SimpleWrapper) getContainer();
    6. ServletRequest sreq = request.getRequest();
    7. ServletResponse sres = response.getResponse();
    8. Servlet servlet = null;
    9. HttpServletRequest hreq = null;
    10. if (sreq instanceof HttpServletRequest) {
    11. hreq = (HttpServletRequest) sreq;
    12. }
    13. HttpServletResponse hres = null;
    14. if (sres instanceof HttpServletResponse) {
    15. hres = (HttpServletResponse) sres;
    16. }
    17. // 分配一个servlet实例来处理请求
    18. try {
    19. servlet = wrapper.allocate();
    20. if (hres != null && hreq != null) {
    21. System.out.println("servlet's classLoader is " + servlet.getClass().getClassLoader().toString());
    22. System.out.println("HttpServlet's classLoader is " + HttpServlet.class.getClassLoader().toString());
    23. servlet.service(hreq, hres);
    24. } else {
    25. servlet.service(sreq, sres);
    26. }
    27. } catch (ServletException e) {
    28. }
    29. }
    30. public String getInfo() {
    31. return null;
    32. }
    33. public Container getContainer() {
    34. return container;
    35. }
    36. public void setContainer(Container container) {
    37. this.container = container;
    38. }
    39. }

    wrapper.allocate()这个方法是调用的SimpleWrapper的allocate方法,allocate会调用loadServlet方法来进行servlet类的类加载,我把代码放这,你可以再看下

    1. public class SimpleWrapper implements Wrapper, Pipeline, Lifecycle {
    2. public SimpleWrapper() {
    3. pipeline.setBasic(new SimpleWrapperValve());
    4. }
    5. // the servlet instance
    6. private Servlet instance = null;
    7. private String servletClass;
    8. private Loader loader;
    9. private String name;
    10. protected LifecycleSupport lifecycle = new LifecycleSupport(this);
    11. private SimplePipeline pipeline = new SimplePipeline(this);
    12. protected Container parent = null;
    13. protected boolean started = false;
    14. public synchronized void addValve(Valve valve) {
    15. pipeline.addValve(valve);
    16. }
    17. public Servlet allocate() throws ServletException {
    18. // Load and initialize our instance if necessary
    19. if (instance == null) {
    20. try {
    21. instance = loadServlet();
    22. } catch (ServletException e) {
    23. throw e;
    24. } catch (Throwable e) {
    25. throw new ServletException("Cannot allocate a servlet instance", e);
    26. }
    27. }
    28. return instance;
    29. }
    30. public Servlet loadServlet() throws ServletException {
    31. if (instance != null) return instance;
    32. Servlet servlet = null;
    33. String actualClass = servletClass;
    34. if (actualClass == null) {
    35. throw new ServletException("servlet class has not been specified");
    36. }
    37. Loader loader = getLoader();
    38. // Acquire an instance of the class loader to be used
    39. if (loader == null) {
    40. throw new ServletException("No loader.");
    41. }
    42. ClassLoader classLoader = loader.getClassLoader();
    43. // Load the specified servlet class from the appropriate class loader
    44. Class classClass = null;
    45. try {
    46. if (classLoader != null) {
    47. classClass = classLoader.loadClass(actualClass);
    48. }
    49. } catch (ClassNotFoundException e) {
    50. throw new ServletException("Servlet class not found");
    51. }
    52. // Instantiate and initialize an instance of the servlet class itself
    53. try {
    54. servlet = (Servlet) classClass.newInstance();
    55. } catch (Throwable e) {
    56. throw new ServletException("Failed to instantiate servlet");
    57. }
    58. // Call the initialization method of this servlet
    59. try {
    60. servlet.init(null);
    61. } catch (Throwable f) {
    62. throw new ServletException("Failed initialize servlet.");
    63. }
    64. return servlet;
    65. }
    66. public Loader getLoader() {
    67. if (loader != null) return (loader);
    68. if (parent != null) return (parent.getLoader());
    69. return (null);
    70. }
    71. }

    SimpleWrapper的getLoader方法会主动去寻找父容器的Loader,所以本次程序我们只要给Context容器设置好Loader就行(WebappLoader)。

    通过loader就能获取到对应的类加载器,也就是WebappClassLoader的实例,然后通过WebappClassLoader去加载该servlet类。

    如果浏览器访问 http://localhost:8080/myApp/Modern,WebappClassLoader实例先加载了 ModernServlet 类,然后ModernServlet的doGet方法被调用,发现需要使用MyObject类,于是JVM拿到ModernServlet的类加载器(即WebappClassLoader实例)去加载MyObject类。

    接下来我们写个启动类,启动一个简易Tomcat,来验证上述说法

    Bootstrap启动类

    本次context容器类使用Tomcat内置的StandardContext,为了验证两个应用的类加载隔离性,这次还将用上StandardHost作为Host容器,Host容器的内容将在第十三章介绍。

    我将构建两个一模一样的StandardContext实例,唯一不同是就是它们加载的应用程序目录不同,一个是myApp,一个是myApp2。理论上来讲,两个应用程序内的类应该由不同的类加载器来加载,接下来启动服务来验证看看

    1. package ex08.pyrmont.startup;
    2. import ex08.pyrmont.core.SimpleWrapper;
    3. import ex08.pyrmont.core.SimpleContextConfig;
    4. import org.apache.catalina.*;
    5. import org.apache.catalina.connector.http.HttpConnector;
    6. import org.apache.catalina.core.StandardContext;
    7. import org.apache.catalina.core.StandardHost;
    8. import org.apache.catalina.loader.WebappClassLoader;
    9. import org.apache.catalina.loader.WebappLoader;
    10. import org.apache.naming.resources.ProxyDirContext;
    11. public final class Bootstrap {
    12. public static void main(String[] args) {
    13. System.setProperty("catalina.base", System.getProperty("user.dir"));
    14. Connector connector = new HttpConnector();
    15. Host host = new StandardHost();
    16. host.setName("localhost");
    17. host.setAppBase("");
    18. {
    19. Wrapper wrapper1 = new SimpleWrapper();
    20. wrapper1.setName("Primitive");
    21. wrapper1.setServletClass("PrimitiveServlet");
    22. Wrapper wrapper2 = new SimpleWrapper();
    23. wrapper2.setName("Modern");
    24. wrapper2.setServletClass("ModernServlet");
    25. Context context = new StandardContext();
    26. // StandardContext's start method adds a default mapper
    27. context.setPath("/myApp");
    28. context.setDocBase("myApp");
    29. context.addChild(wrapper1);
    30. context.addChild(wrapper2);
    31. // context.addServletMapping(pattern, name);
    32. context.addServletMapping("/Primitive", "Primitive");
    33. context.addServletMapping("/Modern", "Modern");
    34. // add ContextConfig. This listener is important because it configures
    35. // StandardContext (sets configured to true), otherwise StandardContext
    36. // won't start
    37. LifecycleListener listener = new SimpleContextConfig();
    38. ((Lifecycle) context).addLifecycleListener(listener);
    39. // here is our loader
    40. Loader loader = new WebappLoader();
    41. // associate the loader with the Context
    42. context.setLoader(loader);
    43. host.addChild(context);
    44. }
    45. {
    46. Wrapper wrapper1 = new SimpleWrapper();
    47. wrapper1.setName("Primitive");
    48. wrapper1.setServletClass("PrimitiveServlet");
    49. Wrapper wrapper2 = new SimpleWrapper();
    50. wrapper2.setName("Modern");
    51. wrapper2.setServletClass("ModernServlet");
    52. Context context = new StandardContext();
    53. // StandardContext's start method adds a default mapper
    54. context.setPath("/myApp2");
    55. context.setDocBase("myApp2");
    56. context.addChild(wrapper1);
    57. context.addChild(wrapper2);
    58. // context.addServletMapping(pattern, name);
    59. context.addServletMapping("/Primitive", "Primitive");
    60. context.addServletMapping("/Modern", "Modern");
    61. // add ContextConfig. This listener is important because it configures
    62. // StandardContext (sets configured to true), otherwise StandardContext
    63. // won't start
    64. LifecycleListener listener = new SimpleContextConfig();
    65. ((Lifecycle) context).addLifecycleListener(listener);
    66. // here is our loader
    67. Loader loader = new WebappLoader();
    68. // associate the loader with the Context
    69. context.setLoader(loader);
    70. host.addChild(context);
    71. }
    72. connector.setContainer(host);
    73. try {
    74. connector.initialize();
    75. ((Lifecycle) connector).start();
    76. ((Lifecycle) host).start();
    77. // make the application wait until we press a key.
    78. System.in.read();
    79. ((Lifecycle) host).stop();
    80. }
    81. catch (Exception e) {
    82. e.printStackTrace();
    83. }
    84. }
    85. }

    启动服务,浏览器访问两下

    1. http://localhost:8080/myApp/Modern
    2. http://localhost:8080/myApp2/Modern

    浏览器的结果与前几章的一样,不再贴了,主要看后端日志

    1. Connected to the target VM, address: '127.0.0.1:64327', transport: 'socket'
    2. HttpConnector Opening server socket on all host IP addresses
    3. HttpConnector[8080] Starting background thread
    4. WebappLoader[/myApp2]: Deploying class repositories to work directory /Users/hml/IdeaProjects/demo/HowTomcatWorks/work/_/localhost/myApp2
    5. WebappLoader[/myApp2]: Deploy class files /WEB-INF/classes to /Users/hml/IdeaProjects/demo/HowTomcatWorks/myApp2/WEB-INF/classes
    6. WebappLoader[/myApp2]: Deploy JAR /WEB-INF/lib/simple-project-1.0-SNAPSHOT.jar to /Users/hml/IdeaProjects/demo/HowTomcatWorks/myApp2/WEB-INF/lib/simple-project-1.0-SNAPSHOT.jar
    7. Starting Wrapper Primitive
    8. Starting Wrapper Modern
    9. StandardManager[/myApp2]: Seeding random number generator class java.security.SecureRandom
    10. StandardManager[/myApp2]: Seeding of random number generator has been completed
    11. WebappLoader[/myApp]: Deploying class repositories to work directory /Users/hml/IdeaProjects/demo/HowTomcatWorks/work/_/localhost/myApp
    12. WebappLoader[/myApp]: Deploy class files /WEB-INF/classes to /Users/hml/IdeaProjects/demo/HowTomcatWorks/myApp/WEB-INF/classes
    13. WebappLoader[/myApp]: Deploy JAR /WEB-INF/lib/simple-project-1.0-SNAPSHOT.jar to /Users/hml/IdeaProjects/demo/HowTomcatWorks/myApp/WEB-INF/lib/simple-project-1.0-SNAPSHOT.jar
    14. Starting Wrapper Primitive
    15. Starting Wrapper Modern
    16. StandardManager[/myApp]: Seeding random number generator class java.security.SecureRandom
    17. StandardManager[/myApp]: Seeding of random number generator has been completed
    18. ModernServlet -- init
    19. =======servlet's classLoader is org.apache.catalina.loader.WebappClassLoader@4bf558aa
    20. =======HttpServlet's classLoader is sun.misc.Launcher$AppClassLoader@18b4aac2
    21. =======MyObject's classLoader is: org.apache.catalina.loader.WebappClassLoader@4bf558aa
    22. =======MyObject print [AAAAAA]
    23. ModernServlet -- init
    24. =======servlet's classLoader is org.apache.catalina.loader.WebappClassLoader@7cca494b
    25. =======HttpServlet's classLoader is sun.misc.Launcher$AppClassLoader@18b4aac2
    26. =======MyObject's classLoader is: org.apache.catalina.loader.WebappClassLoader@7cca494b
    27. =======MyObject print [AAAAAA]

    可以看到 HttpServlet的类加载是应用程序类加载器 AppClassLoader ,并且myApp与myApp2两个应用的AppClassLoader是同一个对象。说明Tomcat中的应用程序类加载器是唯一的,多应用公用的。

    而加载ModernServlet与MyObject两个类的类加载为WebappClassLoader,并且myApp与myApp2两个应用的WebappClassLoader是不同的对象,说明两个应用的类加载是隔离的。

    MyObject类与ModernServlet类使用的类加载相同,也证实了上面的说法,当JVM检测到某类依赖的另外的类需要还没加载时,会拿当前类的类加载器去加载。

    好,Tomcat的载入器内容就到这里,Tomcat的自定义类加载器是一个经典的打破双亲委派机制的案例,目的是为了实现各应用程序之间的类库隔离。

    另外,关于 common、server、shared三个类加载器并不像 WebApp类加载器一样有特定的类(WebappClassLoader)来支撑。Tomcat中并没有类似的诸如CommonClassLoader、ServerClassLoader等类,而是提供了StandardClassLoader类,这三个类加载器都是一个StandardClassLoader类实例,不同的是,他们可加载的类库不同,这个类库就定义在 catalina.properties 文件中,这三个类加载的创建逻辑在org.apache.catalina.startup.Bootstrap#initClassLoaders方法中(基于apache-tomcat-6.09版本)

    org.apache.catalina.startup.Bootstrap部分代码

    1. private void initClassLoaders() {
    2. try {
    3. commonLoader = createClassLoader("common", null);
    4. if( commonLoader == null ) {
    5. // no config file, default to this loader - we might be in a 'single' env.
    6. commonLoader=this.getClass().getClassLoader();
    7. }
    8. catalinaLoader = createClassLoader("server", commonLoader);
    9. sharedLoader = createClassLoader("shared", commonLoader);
    10. } catch (Throwable t) {
    11. log.error("Class loader creation threw exception", t);
    12. System.exit(1);
    13. }
    14. }
    15. private ClassLoader createClassLoader(String name, ClassLoader parent)
    16. throws Exception {
    17. String value = CatalinaProperties.getProperty(name + ".loader");
    18. if ((value == null) || (value.equals("")))
    19. return parent;
    20. ArrayList repositoryLocations = new ArrayList();
    21. ArrayList repositoryTypes = new ArrayList();
    22. int i;
    23. StringTokenizer tokenizer = new StringTokenizer(value, ",");
    24. while (tokenizer.hasMoreElements()) {
    25. String repository = tokenizer.nextToken();
    26. // Local repository
    27. boolean replace = false;
    28. String before = repository;
    29. while ((i=repository.indexOf(CATALINA_HOME_TOKEN))>=0) {
    30. replace=true;
    31. if (i>0) {
    32. repository = repository.substring(0,i) + getCatalinaHome()
    33. + repository.substring(i+CATALINA_HOME_TOKEN.length());
    34. } else {
    35. repository = getCatalinaHome()
    36. + repository.substring(CATALINA_HOME_TOKEN.length());
    37. }
    38. }
    39. while ((i=repository.indexOf(CATALINA_BASE_TOKEN))>=0) {
    40. replace=true;
    41. if (i>0) {
    42. repository = repository.substring(0,i) + getCatalinaBase()
    43. + repository.substring(i+CATALINA_BASE_TOKEN.length());
    44. } else {
    45. repository = getCatalinaBase()
    46. + repository.substring(CATALINA_BASE_TOKEN.length());
    47. }
    48. }
    49. if (replace && log.isDebugEnabled())
    50. log.debug("Expanded " + before + " to " + replace);
    51. // Check for a JAR URL repository
    52. try {
    53. URL url=new URL(repository);
    54. repositoryLocations.add(repository);
    55. repositoryTypes.add(ClassLoaderFactory.IS_URL);
    56. continue;
    57. } catch (MalformedURLException e) {
    58. // Ignore
    59. }
    60. if (repository.endsWith("*.jar")) {
    61. repository = repository.substring
    62. (0, repository.length() - "*.jar".length());
    63. repositoryLocations.add(repository);
    64. repositoryTypes.add(ClassLoaderFactory.IS_GLOB);
    65. } else if (repository.endsWith(".jar")) {
    66. repositoryLocations.add(repository);
    67. repositoryTypes.add(ClassLoaderFactory.IS_JAR);
    68. } else {
    69. repositoryLocations.add(repository);
    70. repositoryTypes.add(ClassLoaderFactory.IS_DIR);
    71. }
    72. }
    73. String[] locations = (String[]) repositoryLocations.toArray(new String[0]);
    74. Integer[] types = (Integer[]) repositoryTypes.toArray(new Integer[0]);
    75. ClassLoader classLoader = ClassLoaderFactory.createClassLoader
    76. (locations, types, parent);
    77. // Retrieving MBean server
    78. MBeanServer mBeanServer = null;
    79. if (MBeanServerFactory.findMBeanServer(null).size() > 0) {
    80. mBeanServer =
    81. (MBeanServer) MBeanServerFactory.findMBeanServer(null).get(0);
    82. } else {
    83. mBeanServer = MBeanServerFactory.createMBeanServer();
    84. }
    85. // Register the server classloader
    86. ObjectName objectName =
    87. new ObjectName("Catalina:type=ServerClassLoader,name=" + name);
    88. mBeanServer.registerMBean(classLoader, objectName);
    89. return classLoader;
    90. }

    org.apache.catalina.startup.ClassLoaderFactory#createClassLoader方法

    1. public static ClassLoader createClassLoader(String locations[],
    2. Integer types[],
    3. ClassLoader parent)
    4. throws Exception {
    5. if (log.isDebugEnabled())
    6. log.debug("Creating new class loader");
    7. // Construct the "class path" for this class loader
    8. ArrayList list = new ArrayList();
    9. if (locations != null && types != null && locations.length == types.length) {
    10. for (int i = 0; i < locations.length; i++) {
    11. String location = locations[i];
    12. if ( types[i] == IS_URL ) {
    13. URL url = new URL(location);
    14. if (log.isDebugEnabled())
    15. log.debug(" Including URL " + url);
    16. list.add(url);
    17. } else if ( types[i] == IS_DIR ) {
    18. File directory = new File(location);
    19. directory = new File(directory.getCanonicalPath());
    20. if (!directory.exists() || !directory.isDirectory() ||
    21. !directory.canRead())
    22. continue;
    23. URL url = directory.toURL();
    24. if (log.isDebugEnabled())
    25. log.debug(" Including directory " + url);
    26. list.add(url);
    27. } else if ( types[i] == IS_JAR ) {
    28. File file=new File(location);
    29. file = new File(file.getCanonicalPath());
    30. if (!file.exists() || !file.canRead())
    31. continue;
    32. URL url = file.toURL();
    33. if (log.isDebugEnabled())
    34. log.debug(" Including jar file " + url);
    35. list.add(url);
    36. } else if ( types[i] == IS_GLOB ) {
    37. File directory=new File(location);
    38. if (!directory.exists() || !directory.isDirectory() ||
    39. !directory.canRead())
    40. continue;
    41. if (log.isDebugEnabled())
    42. log.debug(" Including directory glob "
    43. + directory.getAbsolutePath());
    44. String filenames[] = directory.list();
    45. for (int j = 0; j < filenames.length; j++) {
    46. String filename = filenames[j].toLowerCase();
    47. if (!filename.endsWith(".jar"))
    48. continue;
    49. File file = new File(directory, filenames[j]);
    50. file = new File(file.getCanonicalPath());
    51. if (!file.exists() || !file.canRead())
    52. continue;
    53. if (log.isDebugEnabled())
    54. log.debug(" Including glob jar file "
    55. + file.getAbsolutePath());
    56. URL url = file.toURL();
    57. list.add(url);
    58. }
    59. }
    60. }
    61. }
    62. // Construct the class loader itself
    63. URL[] array = (URL[]) list.toArray(new URL[list.size()]);
    64. if (log.isDebugEnabled())
    65. for (int i = 0; i < array.length; i++) {
    66. log.debug(" location " + i + " is " + array[i]);
    67. }
    68. StandardClassLoader classLoader = null;
    69. if (parent == null)
    70. classLoader = new StandardClassLoader(array);
    71. else
    72. classLoader = new StandardClassLoader(array, parent);
    73. return (classLoader);
    74. }

    关于Tomcat与SpringBoot

    如今我们在用java写Web应用程序时多使用SpringBoot框架,SpringBoot默认集成了Tomcat,这也导致了一个Tomcat中只会部署一个应用程序,自定义类加载器的存在感就大大降低了。

    我写了个测试类来测试了一下

    输出结果

    1. null
    2. sun.misc.Launcher$AppClassLoader@18b4aac2
    3. sun.misc.Launcher$AppClassLoader@18b4aac2
    4. sun.misc.Launcher$AppClassLoader@18b4aac2

    redisTemplate就是我们熟知的那个RedisTemplate,luaService是我自己写的标注了@Service的类,HObject就是一个普普通通不带任何注解的pojo类。

    实验结果就是除了String被启动类加载器加载了,其他的类都是被jdk自带的应用程序类加载器加载的,并且我在这个springboot自带的tomcat的 WebappClassLoaderBase#loadClass 方法上打了断点,发现项目启动后压根没有进入到过这个方法中,也就是WebappClassLoader压根没用上。

    springboot的东西再深挖又得烧脑了,容我休息一下,这里暂且告一段落,后续再做研究。

    源码分享

    https://gitee.com/huo-ming-lu/HowTomcatWorks

    基于原书源码,我改造了Bootstrap以支持启动一个多应用的简易Tomcat。

    我改造了ModernServlet类并加入simple-project-1.0-SNAPSHOT.jar包来验证WebApp应用程序中除servlet类外的其他类的类加载过程。并复制了myApp工程得到myApp2工程,来验证多应用间的类加载隔离。

      

    另附Tomcat各版本源码的下载目录

    https://archive.apache.org/dist/tomcat/

  • 相关阅读:
    神经网络开发
    适用Unreal的本地资源检测功能发布
    核货宝:收银系统后台一般是怎样的,有哪些功能
    八.AV Foundation 视频播放 - 通过手势控制播放器
    Blog2:nchu-software-oop-2022-4+5+期中
    sudo -u root whoami && ****无法用root权限执行后续命令的解决办法
    java毕业设计乐儿乐社区生鲜团购系统源码+lw文档+mybatis+系统+mysql数据库+调试
    论文阅读之Enhancing Transformer with Sememe Knowledge(2020)
    Web应用基础
    从零开始探索C语言(十一)----共用体和位域
  • 原文地址:https://blog.csdn.net/weixin_37557894/article/details/138677646