本文介绍了Java类加载器:为什么首先搜索父类加载器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java中类加载器的正确行为是:

The correct behaviour for a classloader in Java is to:


  1. 如果已加载,则返回类

  2. 调用父loadClass()

  3. 尝试加载类本身。

因此,应始终首先加载系统类路径中定义的类。 Tomcat定义了每个war的类加载器,它将系统类加载器作为父类,因此如果你尝试加载一个类,它将首先查看系统类路径,然后查看war文件中定义的类路径。

So the class defined in the system classpath should always get loaded first. Tomcat defines classloader per war, which has the system classloader as a parent, so if you try to load a class, it will first look in the system classpath and then in the classpath defined in the war file.

根据我的理解,这有两个原因:

As per my understanding, this is for two reasons:


  1. 为了避免不同版本的课程出现问题用过的。想象一下,我在战争中重新定义了java.lang.Object,这将是一场噩梦。

  2. 为了避免对子类加载器的依赖:系统类加载器不能依赖于子类加载器:它很难例如,重新部署战争。

所以,问题是:

除了上述问题之外,实现不首先进行父搜索的类加载器还有其他缺陷吗?

In addition to the above problems, are there any other pitfalls to implementing a classloader which does not do a parent search first?

推荐答案

Tomcat首先不查找父类加载器。实际上它恰恰相反:它首先查看webapp,然后才转到父类加载器(Tomcat 6/7的lib和Tomcat 5.5的共享)。这个规则的例外是系统类(我认为所有包含java。*和javax。*的东西),这些类只在系统类加载器中查找。我相信他们这样做的原因是你说的第一个原因。

Tomcat doesn't looks for a parent classloader first. Actually it does the opposite: it first looks in the webapp and only then goes to the parent classloader (which is "lib" for Tomcat 6/7 and "shared" for Tomcat 5.5). The exception for this rule are the system classes (I think everything that has package java.* and javax.*), these classes were looked only in the system classloader. I believe the reason they do it is the #1 reason you stated.

所以基本上可以实现父优先策略。实现parent-last也没问题。这两种策略都有它们的优点和优点。

So basically it's ok to implement parent-first strategy. It's also ok to implement parent-last. Both strategies have their cons and pros.

我将再给你一个理由,为什么要实现parent-first:你减少了perm内存中加载的类的数量。想象一下,您有多个使用相同库的Web应用程序。使用parent-first将库加载一次。使用parent-last,它将被多次加载。

但是,使用parent-first,所有web-apps都需要使用相同版本的库,而使用parent-last时,它们可能会使用不同的版本。

I'll give you one more reason, why to implement parent-first: you reduce the amount of classes loaded in perm memory. Imagine you have multiple web applications using the same library. With parent-first the library with be loaded once. With parent-last it will be loaded multiple times.
However, with parent-first all web-apps will be required to use the same version of the library, while with parent-last they may use different versions.

这篇关于Java类加载器:为什么首先搜索父类加载器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-12 06:48