`
deepnighttwo
  • 浏览: 52172 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

Find a way out of the ClassLoader maze (1)

 
阅读更多

Find a way out of the ClassLoader maze

System, current, context? Which ClassLoader should you use?

<!--<BLOCKQUOTE><STRONG>Summary</STRONG><BR>--><!--</BLOCKQUOTE>-->By Vladimir Roubtsov


Printer-friendly versionPrinter-friendly version | Send this article to a friendMail this to a friend


Page 1 of 2

<!-- START BIG AD (336x280) jw-articles-336x280.txt -->

<!-- END BIG AD (336x280) -->

June 6, 2003

QWhen should I use
Thread.getContextClassLoader()?

A Although not frequently asked, this question is rather tough to correctly answer. It usually comes up during framework programming, when a good deal of dynamic class and resource loading goes on. In general, when loading a resource dynamically, you can choose from at least three classloaders: the system (also referred to as the application) classloader, the current classloader, and the current thread context classloader. The question above refers to the latter. Which classloader is the right one?

One choice I dismiss easily: the system classloader. This classloader handles -classpath and is programmatically accessible as ClassLoader.getSystemClassLoader(). All ClassLoader.getSystemXXX() API methods are also routed through this classloader. You should rarely write code that explicitly uses any of the previous methods and instead let other classloaders delegate to the system one. Otherwise, your code will only work in simple command-line applications, when the system classloader is the last classloader created in the JVM. As soon as you move your code into an Enterprise JavaBean, a Web application, or a Java Web Start application, things are guaranteed to break.

So, now we are down to two choices: current and context classloaders. By definition, a current classloader loads and defines the class to which your current method belongs. This classloader is implied when dynamic links between classes resolve at runtime, and when you use the one-argument version of Class.forName(), Class.getResource(), and similar methods. It is also used by syntactic constructs like X.class class literals (see "Get a Load of That Name!" for more details).

Thread context classloaders were introduced in Java 2 Platform, Standard Edition (J2SE). Every Thread has a context classloader associated with it (unless it was created by native code). It is set via the Thread.setContextClassLoader() method. If you don't invoke this method following a Thread's construction, the thread will inherit its context classloader from its parent Thread. If you don't do anything at all in the entire application, all Threads will end up with the system classloader as their context classloader. It is important to understand that nowadays this is rarely the case since Web and Java 2 Platform, Enterprise Edition (J2EE) application servers utilize sophisticated classloader hierarchies for features like Java Naming and Directory Interface (JNDI), thread pooling, component hot redeployment, and so on.

Why do thread context classloaders exist in the first place? They were introduced in J2SE without much fanfare. A certain lack of proper guidance and documentation from Sun Microsystems likely explains why many developers find them confusing.

In truth, context classloaders provide a back door around the classloading delegation scheme also introduced in J2SE. Normally, all classloaders in a JVM are organized in a hierarchy such that every classloader (except for the primordial classloader that bootstraps the entire JVM) has a single parent. When asked to load a class, every compliant classloader is expected to delegate loading to its parent first and attempt to define the class only if the parent fails.

Sometimes this orderly arrangement does not work, usually when some JVM core code must dynamically load resources provided by application developers. Take JNDI for instance: its guts are implemented by bootstrap classes in rt.jar (starting with J2SE 1.3), but these core JNDI classes may load JNDI providers implemented by independent vendors and potentially deployed in the application's -classpath. This scenario calls for a parent classloader (the primordial one in this case) to load a class visible to one of its child classloaders (the system one, for example). Normal J2SE delegation does not work, and the workaround is to make the core JNDI classes use thread context loaders, thus effectively "tunneling" through the classloader hierarchy in the direction opposite to the proper delegation.

By the way, the previous paragraph may have reminded you of something else: Java API for XML Parsing (JAXP). Yes, when JAXP was just a J2SE extension, the XML parser factories used the current classloader approach for bootstrapping parser implementations. When JAXP was made part of the J2SE 1.4 core, the classloading changed to use thread context classloaders, in complete analogy with JNDI (and confusing many programmers along the way). See what I mean by lack of guidance from Sun?

After this introduction, I have come to the crux of the matter: neither of the remaining two choices is the right one under all circumstances. Some believe that thread context classloaders should become the new standard strategy. This, however, creates a very messy classloading picture if various JVM threads communicate via shared data, unless all of them use the same context loader instance. Furthermore, delegating to the current classloader is already a legacy rule in some existing situations like class literals or explicit calls to Class.forName() (which is why, by the way, I recommend (again, see "Get a Load of That Name!") avoiding the one-argument version of this method). Even if you make an explicit effort to use only context loaders whenever you can, there will always be some code not under your control that delegates to the current loader. This uncontrolled mixing of delegation strategies sounds rather dangerous.

To make matters worse, certain application servers set context and current classloaders to different ClassLoader instances that have the same classpaths and yet are not related as a delegation parent and child. Take a second to think about why this is particularly horrendous. Remember that the classloader that loads and defines a class is part of the internal JVM's ID for that class. If the current classloader loads a class X that subsequently executes, say, a JNDI lookup for some data of type Y, the context loader could load and define Y. This Y definition will differ from the one by the same name but seen by the current loader. Enter obscure class cast and loader constraint violation exceptions.

This confusion will probably stay with Java for some time. Take any J2SE API with dynamic resource loading of any kind and try to guess which loading strategy it uses. Here is a sampling:

  • JNDI uses context classloaders
  • Class.getResource() and Class.forName() use the current classloader
  • JAXP uses context classloaders (as of J2SE 1.4)
  • java.util.ResourceBundle uses the caller's current classloader
  • URL protocol handlers specified via java.protocol.handler.pkgs system property are looked up in the bootstrap and system classloaders only
  • Java Serialization API uses the caller's current classloader by default

Those class and resource loading strategies must be the most poorly documented and least specified area of J2SE. <!-- break --><!-- PAGECOUNT 2 -->

Next page >
Page 1 Find a way out of the ClassLoader maze
Page 2 What is a Java programmer to do?
<!-- REPLACE TALKBACK -->

Printer-friendly versionPrinter-friendly version | Send this article to a friendMail this to a friend

<!-- REPLACE BIO -->

分享到:
评论

相关推荐

    Understanding the Java ClassLoader

    - **加载类**:编译完成后,使用自定义ClassLoader的findClass方法加载编译后的类。 **3. 示例代码框架** ```java public class AutoCompileClassLoader extends ClassLoader { // 定义加载类的方法 @Override ...

    自定义classloader的使用

    创建自定义Classloader需要继承java.lang.ClassLoader类,并重写其关键方法,如`findClass(String name)`或`loadClass(String name)`。这两个方法分别用于查找指定类的字节码和实际加载类。在`findClass`中,我们...

    ClassLoader

    ### Java虚拟机中ClassLoader概述与双亲委托机制详解 #### 一、ClassLoader概念与作用 在Java编程语言中,`ClassLoader`是一个非常重要的组件,它负责加载程序运行所需的类文件到Java虚拟机(JVM)中。`ClassLoader`...

    ClassLoader运行机制 自己写的

    1. 如果WebApp ClassLoader的缓存中没有类A,则会查找System ClassPath,未找到A。 2. 接下来查找Application Class Path,如果在其中找到了A(如在wsdl4j.jar中),则加载该类。 3. 如果Application Class Path也...

    ClassLoader小例子

    1. **ClassLoader的基本概念** - 类加载器是Java中的一个核心组件,它负责将类的.class文件加载到JVM中,并转换为可执行的Java对象。 - Java的类加载机制遵循“双亲委派模型”,即一个类加载请求会先由顶级的...

    classloader

    Java ClassLoader是Java运行时系统的关键但经常被忽视的组件,负责在运行时查找和加载类文件。通过创建自定义ClassLoader,你可以定制JVM,使类文件的引入方式完全重新定义,这提供了很多实用和有趣的可能。这篇教程...

    ClassLoader 案例

    在Java编程语言中,ClassLoader是核心组件之一,它负责加载类到JVM(Java虚拟机)中。自定义ClassLoader允许开发者根据特定需求加载类,比如动态加载或更新类文件,这在某些高级应用场景中非常有用,如插件系统、热...

    Java ClassLoader定制实例

    1. 安全性:自定义ClassLoader可能导致安全问题,因为它可以加载任意的类,因此需要确保加载的类是可信的。 2. 类的可见性:不同的ClassLoader加载的类相互之间默认是不可见的,除非使用` ProtectionDomain`进行设置...

    ClassLoader 详解.doc

    1. Bootstrap ClassLoader:引导类加载器,也称为原始类加载器。它是整个加载过程的起点,负责加载Java的核心类库,如rt.jar,这是Java运行环境的基础。Bootstrap ClassLoader并非继承自java.lang.ClassLoader,而是...

    理解Java ClassLoader机制

    自定义ClassLoader需要继承`java.lang.ClassLoader`类,并重写`findClass()`或`loadClass()`方法。通过这两个方法,你可以控制类的加载来源和方式。 在实际开发中,理解ClassLoader机制可以帮助解决一些问题,例如...

    深入理解ClassLoader工作机制.docx

    1. **加载**:加载是ClassLoader工作的起点,它从文件系统或网络中找到类的二进制数据,然后创建一个对应的Class对象。这个过程可以通过自定义ClassLoader来实现,比如从数据库中加载类。 2. **验证**:验证是确保...

    java ClassLoader机制及其在OSGi中的应用

    1. 每个OSGi bundle都有自己的ClassLoader,用于加载该bundle中的类,这使得不同bundle之间的类隔离得以实现,避免了类冲突。 2. OSGi的ClassLoader支持动态加载和卸载bundle,当bundle被激活或停用时,对应的类...

    深入java虚拟机(inside the java virtual machine)

    java虚拟机的运行机理的详细介绍 Inside the Java Virtual Machine Bill Venners $39.95 0-07-913248-0 Inside the Java Virtual ... Slices of Pi: A Simulation of the Java Virtual Machine Index About the Author

    Understanding the Java ClassLoader.pdf

    本文档提到的“编译时类加载器”(The Compiling ClassLoader)实际上是指在加载类的同时执行编译操作的类加载器。这种类型的类加载器可以实现在运行时自动编译源代码,并将生成的字节码加载到JVM中。这种能力对于...

    JVM ClassLoader简析

    首先,ClassLoader可以分为三种基本类型:Bootstrap ClassLoader、Extension ClassLoader和Application ClassLoader。Bootstrap ClassLoader是JVM启动时的第一个ClassLoader,负责加载JDK的`&lt;JAVA_HOME&gt;\lib`目录下...

    ClassLoader类加载机制和原理详解

    在Java编程语言中,ClassLoader是核心组件之一,它负责加载类到JVM(Java虚拟机)中执行。本文将深入探讨ClassLoader的工作原理和类加载机制,帮助开发者理解这个至关重要的概念。 1. 类加载机制概述 Java的类加载...

Global site tag (gtag.js) - Google Analytics