Find a way out of the classloader maze (1)

Source: Internet
Author: User
Tags bootstrap classes xml parser
Find a way out of the classloader Maze system, current, context? Which classloader shocould you use?

By Vladimir roubtsov


Printer-friendly version | mail this to a friend

Page 1 of 2

 
 

 

June 6 and 2003

When shoshould I use
Thread. getcontextclassloader ()?

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 Cl Assloader, 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 shoshould 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 u Sed 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 thread S 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 emerge 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 too such that every classloader (should t forPrimordialClassloader 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 callfor 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 extends tively "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 extends 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 shoshould 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. fu Rthermore, delegating to the current classloader is already a legacy rule in some existing situations like class literals or explicit CALS 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 Special 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 cocould 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 ()AndClass. forname ()Use the current classloader
    • JAXP uses context classloaders (as of j2se 1.4)
    • Java. util. resourcebundleUses the caller's current classloader
    • URL protocol handlers specifiedJava. 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 specified ented and least specified area of j2se.

Next page>
Page 1 find a way out of the classloader maze
Page 2 What is a Java programmer to do?

Printer-friendly version | mail this to a friend

    Resources
  • Download the source code for all classes discussed in this article:
    Http://www.javaworld.com/javaworld/javaqa/2003-06/load/01-qa-0606-load.zip
  • "Get a load of that name! "Vladimir roubtsov (Javaworld,March 2003 ):
    Http://www.javaworld.com/javaworld/javaqa/2003-03/01-qa-0314-forname.html
  • Ted neward's "Understanding class. forname ()" examines similar topics in great detail:
    Http://www.javageeks.com/Papers/ClassForName/index.html
  • Sun's bug database contains multiple issues related to getcontextclassloader. See these Bug IDs, for example (requires login): 4648098,463 0895, 4452042,434 0158, 4155645:
    Http://developer.java.sun.com/developer/bugParade/
  • Want more? SeeJava Q &Index page for the full Q & A catalog:
    Http://www.javaworld.com/columns/jw-qna-index.shtml
  • For more than 100 insightful Java tips, visitJavaworld'SJava tipsIndex page:
    Http://www.javaworld.com/columns/jw-tips-index.shtml
  • BrowseJava 2 platform, Standard EditionSectionJavaworld'S topical index:
    Http://www.javaworld.com/channel_content/jw-j2se-index.shtml? J2se
  • BrowseJava Virtual MachineSectionJavaworld'S topical index:
    Http://www.javaworld.com/channel_content/jw-jvm-index.shtml

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.