June 6, 2003

Q: When 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.

Learn Java from beginning concepts to advanced design patterns in this comprehensive 12-part course! ]

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.pkgssystem 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.

What is a Java programmer to do?

If your implementation is confined to a certain framework with articulated resource loading rules, stick to them. Hopefully, the burden of making them work will be on whoever has to implement the framework (such as an application server vendor, although they don't always get it right either). For example, always use Class.getResource() in a Web application or an Enterprise JavaBean.

In other situations, you might consider using a solution I have found useful in personal work. The following class serves as a global decision point for acquiring the best classloader to use at any given time in the application (all classes shown in this article are available with the download):

  1. public abstract class ClassLoaderResolver
  2. {
  3. /**
  4. * This method selects the best classloader instance to be used for
  5. * class/resource loading by whoever calls this method. The decision
  6. * typically involves choosing between the caller's current, thread context,
  7. * system, and other classloaders in the JVM and is made by the {@link IClassLoadStrategy}
  8. * instance established by the last call to {@link #setStrategy}.
  9. *
  10. * @return classloader to be used by the caller ['null' indicates the
  11. * primordial loader]
  12. */
  13. public static synchronized ClassLoader getClassLoader ()
  14. {
  15. final Class caller = getCallerClass (0);
  16. final ClassLoadContext ctx = new ClassLoadContext (caller);
  17.  
  18. return s_strategy.getClassLoader (ctx);
  19. }
  20. public static synchronized IClassLoadStrategy getStrategy ()
  21. {
  22. return s_strategy;
  23. }
  24. public static synchronized IClassLoadStrategy setStrategy (final IClassLoadStrategy strategy)
  25. {
  26. final IClassLoadStrategy old = s_strategy;
  27. s_strategy = strategy;
  28.  
  29. return old;
  30. }
  31.  
  32. /**
  33. * A helper class to get the call context. It subclasses SecurityManager
  34. * to make getClassContext() accessible. An instance of CallerResolver
  35. * only needs to be created, not installed as an actual security
  36. * manager.
  37. */
  38. private static final class CallerResolver extends SecurityManager
  39. {
  40. protected Class [] getClassContext ()
  41. {
  42. return super.getClassContext ();
  43. }
  44.  
  45. } // End of nested class
  46.  
  47. /*
  48. * Indexes into the current method call context with a given
  49. * offset.
  50. */
  51. private static Class getCallerClass (final int callerOffset)
  52. {
  53. return CALLER_RESOLVER.getClassContext () [CALL_CONTEXT_OFFSET +
  54. callerOffset];
  55. }
  56.  
  57. private static IClassLoadStrategy s_strategy; // initialized in
  58.  
  59. private static final int CALL_CONTEXT_OFFSET = 3; // may need to change if this class is redesigned
  60. private static final CallerResolver CALLER_RESOLVER; // set in
  61.  
  62. static
  63. {
  64. try
  65. {
  66. // This can fail if the current SecurityManager does not allow
  67. // RuntimePermission ("createSecurityManager"):
  68.  
  69. CALLER_RESOLVER = new CallerResolver ();
  70. }
  71. catch (SecurityException se)
  72. {
  73. throw new RuntimeException ("ClassLoaderResolver: could not create CallerResolver: " + se);
  74. }
  75.  
  76. s_strategy = new DefaultClassLoadStrategy ();
  77. }
  78. } // End of class.

You acquire a classloader reference by calling the ClassLoaderResolver.getClassLoader() static method and use the result to load classes and resources via the normal java.lang.ClassLoader API. Alternatively, you can use this ResourceLoader API as a drop-in replacement for java.lang.ClassLoader:

  1. public abstract class ResourceLoader
  2. {
  3. /**
  4. * @see java.lang.ClassLoader#loadClass(java.lang.String)
  5. */
  6. public static Class loadClass (final String name)
  7. throws ClassNotFoundException
  8. {
  9. final ClassLoader loader = ClassLoaderResolver.getClassLoader (1);
  10.  
  11. return Class.forName (name, false, loader);
  12. }
  13. /**
  14. * @see java.lang.ClassLoader#getResource(java.lang.String)
  15. */
  16. public static URL getResource (final String name)
  17. {
  18. final ClassLoader loader = ClassLoaderResolver.getClassLoader (1);
  19.  
  20. if (loader != null)
  21. return loader.getResource (name);
  22. else
  23. return ClassLoader.getSystemResource (name);
  24. }
  25. ... more methods ...
  26. } // End of class

The decision of what constitutes the best classloader to use is factored out into a pluggable component implementing the IClassLoadStrategy interface:

  1. public interface IClassLoadStrategy
  2. {
  3. ClassLoader getClassLoader (ClassLoadContext ctx);
  4. } // End of interface

To help IClassLoadStrategy make its decision, it is given a ClassLoadContext object:

  1. public class ClassLoadContext
  2. {
  3. public final Class getCallerClass ()
  4. {
  5. return m_caller;
  6. }
  7.  
  8. ClassLoadContext (final Class caller)
  9. {
  10. m_caller = caller;
  11. }
  12.  
  13. private final Class m_caller;
  14. } // End of class

ClassLoadContext.getCallerClass() returns the class whose code calls into ClassLoaderResolver or ResourceLoader. This is so that the strategy implementation can figure out the caller's classloader (the context loader is always available as Thread.currentThread().getContextClassLoader()). Note that the caller is determined statically; thus, my API does not require existing business methods to be augmented with extra Class parameters and is suitable for static methods and initializers as well. You can augment this context object with other attributes that make sense in your deployment situation.

All of this should look like a familiar Strategy design pattern to you. The idea is that decisions like "always context loader" or "always current loader" get separated from the rest of your implementation logic. It is hard to know ahead of time which strategy will be the right one, and with this design, you can always change the decision later.

I have a default strategy implementation that should work correctly in 95 percent of real-life situations:

Find a way out of the ClassLoader maze的更多相关文章

  1. 【译文】走出Java ClassLoader迷宫 Find a way out of the ClassLoader maze

    本文是一篇译文.原文:Find a way out of the ClassLoader maze 对于类加载器,普通Java应用开发人员不需要了解太多.但对于系统开发人员,正确理解Java的类加载器 ...

  2. 使用自定义 classloader 的正确姿势

    详细的原理就不多说了,网上一大把, 但是, 看了很多很多, 即使看了jdk 源码, 说了罗里吧嗦, 还是不很明白: 到底如何正确自定义ClassLoader, 需要注意什么 ExtClassLoade ...

  3. Atitti 载入类的几种方法    Class.forName ClassLoader.loadClass  直接new

    Atitti 载入类的几种方法    Class.forName ClassLoader.loadClass  直接new 1.1. 载入类的几种方法    Class.forName ClassLo ...

  4. java笔记--理解java类加载器以及ClassLoader类

    类加载器概述: java类的加载是由虚拟机来完成的,虚拟机把描述类的Class文件加载到内存,并对数据进行校验,解析和初始化,最终形成能被java虚拟机直接使用的java类型,这就是虚拟机的类加载机制 ...

  5. Backtracking algorithm: rat in maze

    Sept. 10, 2015 Study again the back tracking algorithm using recursive solution, rat in maze, a clas ...

  6. Class.forName和ClassLoader.loadClass等

    Class类 首先,Class类里可以记载所有类的属性.方法等信息.这个也就是运行时类别标记,它记录了所有的对象(比如int,MyClass,void,数组等等)对应的类信息. Class对象 JVM ...

  7. Java ClassLoader 原理详细分析(转)

    转载自:http://www.codeceo.com/article/java-classloader.html 一.什么是ClassLoader? 大家都知道,当我们写好一个Java程序之后,不是管 ...

  8. [Tomcat] Tomcat的classloader

    定义 同其他服务器应用一样,tomcat安装了各种classloader(classes that implement java.lang.ClassLoader) Bootstrap | Syste ...

  9. java中Class.forName("xxx")和ClassLoader().loadClass("xxx")的区别

    一.首先,查看Class类中的forName方法,可以发现有如下三个方法,但是我们通常用的是只有一个参数的方法. 简单介绍一下这三个方法: 第一个方法Class.forName("xxx&q ...

随机推荐

  1. 下载安装tomcat和jdk,配置运行环境,与Intellij idea 2017关联

    第一篇博客,最近公司要用java和jsp开发新的项目,第一次使用Intellij idea 2017,有很多地方需要一步步配置,有些按照网上的教程很快就配置好了,有的还是琢磨了一会儿,在这里做一个记录 ...

  2. vs2013 报错error C1083: 无法打开包括文件:“gl\glew.h”: No such file or directory\

    vs报错诸如如无法打开“gl\xxx.h”时, 解决方法: 1.去http://glew.sourceforge.net/下载相关文件,2.在下载下来的文件里找到xxx.h,将其复制到vs的相关目录下 ...

  3. 深入理解 java I/O

    Java 的 I/O 类库的基本架构 I/O 问题是任何编程语言都无法回避的问题,可以说 I/O 问题是整个人机交互的核心问题,因为 I/O 是机器获取和交换信息的主要渠道.在当今这个数据大爆炸时代, ...

  4. 关于UTC时间和本地时间

    收藏了个类Publics  可以实现本地时间和UTC时间的转换 UCT时间=本地时间-8    本地时间比UTC时间快8小时 element-ui的日期选择器上  选择的时间显示的是本地时间   但实 ...

  5. Qt--信号槽传递自定义结构体参数

    自定义结构体参数的信号槽连接 (1) 对于自定义的结构体参数,信号槽无法识别参数,导致信号槽连接不起作用.所以需要注册结构体参数.在结构体中声明结束的地方加上结构体注册. struct DealDet ...

  6. ECharts图表的小工具

    本文介绍一个echarts工具类EChart.js,用来制作统计图表,基于echarts3. 一.工具类特性如下: 包含柱状图.折线图和饼图,可以实现这三类统计图之间的切换: 支持标题和副标题: 支持 ...

  7. cocos2dx AudioEngine在Android7上播放音效卡顿问题处理

    1.此问题在cocos2dx 3.13/3.14版本(其它版本没有测试过)在Android7中使用AudioEngine的play2d函数播放音效时出现. 调试时出现如下提示: 2.论坛中相关讨论帖地 ...

  8. 算法笔记--最大流和最小割 && 最小费用最大流 && 上下界网络流

    最大流: 给定指定的一个有向图,其中有两个特殊的点源S(Sources)和汇T(Sinks),每条边有指定的容量(Capacity),求满足条件的从S到T的最大流(MaxFlow). 最小割: 割是网 ...

  9. (转)UCOSII在任务切换与出入中断时堆栈指针的使用

    1 uc/os ii在M3中的堆栈结构 1.1 M3入账序列  1.2 加上手工入栈序列  2 PendSV在Cortex-M3中的应用 Systick为嵌入到内核中,优先级比一般中断优先级高.若在一 ...

  10. Lab 5-1

    Analyze the malware found in the file Lab05-01.dll using only IDA Pro. The goal of this lab is to gi ...