Java Class Loader

12/02/2012

Java ClassLoader loads a java class file into java virtual machine. It is as simple as that. It is not a huge complicated concept to learn and every java developer must know about the java class loaders and how it works.

Like NullPointerException, one exception that is very popular is ClassNotFoundException. At least in your beginner stage you might have got umpteen number of ClassNotFoundException. Java class loader is the culprit that is causing this exception.

Types (Hierarchy) of Java Class Loaders

Java class loaders can be broadly classified into below categories:

  • Bootstrap Class Loader
    Bootstrap class loader loads java’s core classes like java.lang, java.util etc. These are classes that are part of java runtime environment. Bootstrap class loader is native implementation and so they may differ across different JVMs.
  • Extensions Class Loader
    JAVA_HOME/jre/lib/ext contains jar packages that are extensions of standard core java classes. Extensions class loader loads classes from this ext folder. Using the system environment propery java.ext.dirs you can add ‘ext’ folders and jar files to be loaded using extensions class loader.
  • System Class Loader
    Java classes that are available in the java classpath are loaded using System class loader.

You can see more class loaders like java.net.URLClassLoader, java.security.SecureClassLoader etc. Those are all extended from java.lang.ClassLoader

These class loaders have a hierarchical relationship among them. Class loader can load classes from one level above its hierarchy. First level is bootstrap class loader, second level is extensions class loader and third level is system class loader.

Class Self Reference

When a java source file is compiled to a binary class, compiler inserts a field into java class file. It is a public static final field named ‘class’ of type java.lang.Class

So for all java classes you can access it as java.lang.Class classObj = ClassName.class;

Ads by Google

Significance of this Class object is it contains a method getClassLoader() which returns the class loader for the class. It will return null it it was loaded by bootstrap class loader.

How a Java Class Loader Works?

When a class name is given, class loader first locates the class and then reads a class file of that name from the native file system. Therefore this loading process is platform dependent.

By default java.lang.ClassLoader is registered as a class loader that is capable of loading classes in parallel. But the subclasses needs to register as parallel or not at the time of instantiation.

Classes can also be loaded from network, constructed on runtime and loaded. ClassLoader class has a method name defineClass which takes input as byte array and loads a class.

Class Loader Parent

All class loaders except bootstrap class loader has a parent class loader. This parent is not as in parent-child relationship of inheritance. Every class loader instance is associated with a parent class loader.

When a class loader is entrusted with the responsibility of loading a class, as a first step it delegates this work to the associated parent class loader. Then this parent class loader gets the instruction and sequentially it delegates the call to its parent class loader. In this chain of hierarchy the bootstrap class loader is at the top.

When a class loader instance is created, using its constructor the parent classloader can be associated with it.

Class Loader Rule 1

A class is loaded only once into the JVM.

In this rule, what is “a class”? Uniqueness of a class is identified along with the ClassLoader instance that loaded this class into the JVM. A class is always identified using its fully qualified name (package.classname). So when a class is loaded into JVM, you have an entry as (package, classname, classloader). Therefore the same class can be loaded twice by two different ClassLoader instances.

I will be writing some more articles on custom class loaders, jar hell and internals of class loading like loading-linking.

This Core Java tutorial was posted on 12/02/2012.
Ads by Google

159 comments on “Java Class Loader

  1. nice article…never read this before…good to know this..thank you so much Joe

  2. Nice article, will wait for the next article in this series.

  3. Please continue your work(service). Thanks.
    Can you please write about spring, hibernate framework?

  4. Thank you for good article provided Joe………..

  5. Hi Joe, All your papers are very good and informative. You make your point clear in all the topics you cover.My sincere thanks and wishes for your work. Keep sharing your knowledge. Best wishes.

  6. nice explanation, very helpful for me…:)

  7. it was real awesome:-)
    but i have one question

    java use magic number, minor version,major version is this all link to jvm to load a class

  8. Following is not clear:

    “Extensions Class Loader”

    Pl give examples of some existing extensions.

    Rao

  9. waiting for the next article..
    going great and thank you very much

  10. @Karan, class loader uses fully qualified name and ClassLoader reference together as a unique key to avoid duplicate loading of classes.

    You are mixing serialization with this.

    magic number is written to the stream header to denote that is start of serialzed content. refer serialization

    also:
    u4 magic;
    u2 minor_version;
    u2 major_version;
    in a java binary class

  11. Sorry to say this article is not as well explained as all others on your website..
    There are no examples to understand properly..
    but still brief & well written..

  12. i go throw your article, it is really awesome. i got great knowledge.
    thanks……

  13. Its Good Joe. I appreciate your passion towards sharing knowledge.

    IS there any possibility that I can provide some support to you in writing an articles.

  14. it’svery good articale..but need some more clarity in this

  15. Good Article….But as a beginner, I need some code snippet to understand the concept more lively….
    Thanks for posting….

  16. thnx joe i got…and all ur post are very nice

  17. Style of explanations is superb in all the topics.. so good explanation.. :) but only this topic, i felt some less clarity about the usage of java.lang.ClassLoader programmatically .. :|

  18. it’s very good article.But need some more clarity in this

  19. Nice Information provided you !!!
    this info.is helpful to my seminar

  20. Hi Joe, could you please elaborate on ClassLoader roule. I am little confused.
    Thx

  21. informative post indeed… I was looking for such post… I’m all new to this world and being enrolled in a core java course was looking for such valuable insights.. thanks :)

  22. thanks for the blog joe, good work, keep it up

    regards
    zubair

  23. Simple and clear explanation. Thanks :)

  24. Nice Explanation joe.

    thank you.

  25. Hi Joe,

    I have one question regarding this topic.
    We normally say that Singleton is for each class. If singleton class is loaded by different classloader then it will create more than one object, which defeats the design pattern purpose.

    But how different classloader can load the defined singleton class. As you mentioned there are only 3 types of Classloader and system class loader is responsible for loading all the classes.

  26. Nice explanation…Very usefull….
    Thanks a lot…

  27. Really helpful to understand in deep what is going in the inside.Thanks a lot and wish you do more…!!

  28. vry useful sir…as always.
    waiting for rest part of article .
    Thanx

  29. Nice article. Just a feedback.
    I don’t know if anyone has already given this feedback or not(there are lots of comments!), but it should read “java.lang.Class” and not “java.lang.class”(note the capital C) in the section Class Self Reference. It may confuse the newbies!

  30. Thats really very useful information..
    can u pls explain what is context-root? and why it s required

  31. thanq for your explanation joe..awaiting more interesting topics from you

  32. interesting to read it .never read abt it before . good job joe

  33. plz joe Discuss abt the HASHCODE for object i have very doubt in that . what exactly hash code and where its exist

  34. plz joe Discuss abt the HASHCODE for object i have plenty of doubt in that . what exactly hash code and where its exist ????

  35. Thanku very much for this kind of java stuff.You are working really good.

  36. I never knew so much in depth about class loaders. I just knew that they load classes after at runtime….. Now i know the diff types of class loaders and how it actually works….I am looking to go to a java field in my company.. hope it helps… Thanks Joe .

  37. really vry intersting topic filled wid lots of knowledge…Joe u described it vry beautifully…lookng for the next article of the same series.. :)

  38. I read so many articles from other link in google.com but never got the idea so clearly as its explained here … Thanks you so much for making our life so easy !! :)

    Regards,
    GN

  39. Hi Joe,

    Had a quick question. I want to define my own classloader for loading classes from specific locations defined at runtime. From what I have read and understood, I think I’d have to define the default classloader as the parent of my own classloader and then give the FQCN of my classloader as value of “-D” option in java command. Am i right till here? if yes, how do I put the default classloader as parent of my own classloader?

    Regards,
    Indraneel

  40. Good article Joe. I have been finding info about class loader and finally got it. Thanks…

    Satya

  41. Insightful Joe.
    The pictorial illustration was good.
    a more apt picture can still be employed.
    Nice work, Man.

  42. Hi Joe,
    This was a great piece of information. Thanks for the post…

    King Regards,
    Anoop Shiralige

  43. Hi joe,
    Thanks for wonderful article, could you please write the follow up article on class loader which you mentioned, thanks in advance. Keep up the excellent work!

  44. give more programmatic explanation on ClassLoader.

  45. Nice article.Better to explore the the classloader at server level.

  46. Really nice and very help full artical. kindly explore all these things in more details.

  47. HI JOe,
    Thanks for explanation.This is nice article for all java beginners.Most of the people thinks like java is big ocean but you told small piece.

    Thanks,
    Audiseshaiah

  48. Hi Joe,

    Nice to have this article.
    Continue with this please …
    Expecting more like this ….
    Appreciate your help …

  49. Hi Joe,

    Nice to have this article.
    Continue with this please …
    Expecting more like this ….
    Appreciate your help …

  50. If during compilation compiler inserts public static final field named ‘class’ , then why is it not accessible through java.lang.reflect API(using getField() method) ?

  51. such a good article ….thank you Joe sir.

  52. Good one …. Interesting and Informative …
    Hats off Joe ..
    Avinash Anand

  53. hey awesome information….thanks for the post

  54. Hi Joe,

    Thanks for your explanation.I have one doubt.

    *** A class is loaded only once into the JVM.

    *** Therefore the same class can be loaded twice by two different Class Loader instances.

    Could you please describe more…..

    Thanks.

  55. nice article…as m at entry level so it is very helpfull to me….

    nice work…thanx :)

  56. Joe i am having one doubt.

    youd hav mentioned that same class can be loaded twice by two different ClassLoader instances.

    Is it possible to load same class with same package name with the two different instances of same ClassLoader.

  57. Hi Joe,

    Thanks for provding this information however this could have been a better one. If possible please add some examples and use cases.

    Thanks

  58. nice article Joe

    I am unable to understand one Thing..
    id classLoader is diff for every class

  59. It is really nice article of class loader.

    Can you explain if i have used in my main method class 2 other classed (My own class).

    Than how these class will be loaded in jvm means parallerly or as they will come in code.

    Please reply at pankajmangal2007@gmail.com if possible

  60. can u pleaes help me how to desin class loader in java and hoe to execute it

    please its urgent………..

  61. it very good explanation joe, expecting from you more java design level

  62. This article has saved my life! I was totally *this close* to kicking the bucket. Thanks Joe.

  63. This explanation is very… best
    Thanks JOE Sir

  64. Here Explanation of ClassLoader is best concept….
    Thanks JOE Sir

  65. Very useful content.
    Can we get some example on Spring, Struts and hibernate?

  66. it’s very good artical about class loader…

  67. Hi Joe,

    Good question for you !

    I have to use a jar file which is built using Spring 2.5 in an application which is using spring 3. Do you think it will cause any issues. It would be great if you can explain a bit more in either case.

    Thanks !

  68. Superbbbb…..Never seen such type of articles…..waitinggggggg for next….

  69. Great Article.. Helped me to understand ClassLoaders.. Thanks a lot..

  70. Great Article.. Helped me to understand ClassLoaders.. Thanks a lot..

  71. Hi,

    You said ” parent class loader gets the instruction and sequentially it delegates the call to its parent class loader. In this chain of hierarchy the bootstrap class loader is at the top.”
    Let me understand, does this mean that for every class loading, child goes to its parent(i.e ultimately to the bootstrap).
    -> If yes, then it means all the classes are finally loaded by the bootstrap class loader itself. Then, why do we need child?

    -> If no, then it could mean that some of the information needed by the child is given by the parent class loader. What is that information?

  72. i have face a problem some days back.
    one class loader already load a class.after thAT another class loader try to load same class in same mechine that time i got error.
    it is very use full for me.

  73. thanks for your tutorial.., it helps me a lot to know about java class loader..,

  74. Hey Joe really nice article.
    Any chance I contact you on your email & discuss as well generally.

  75. good after noon sir,
    really this article is very good please carry on…….
    thankyou

  76. Really very informative and im looking for the post from you about java class Exception’s….:)

  77. excellent article, now I got an idea about class loaders and how same class can be loaded by two different class loaders

  78. Very good information. Please keep it up !

  79. Its really very excellent Article…
    Thanks A Lot

  80. Thank you for providing good explanation.
    Sir, Please tell me who is responsible to
    load ClassLoader class

  81. Pingback: JDBC Introduction

  82. This is Mahesh

    Super’b articles are posted in this blog…………
    keep on posting

  83. hi joe you said simple but moreinfermation getting

  84. hi I want to list all classes in a swf file , how can i do it with JAVA ? Thanks .

  85. Hi,
    Nice article,
    I have one question,
    I want to load jar on run time when already one jar of same name is loaded in jvm.
    Example-
    Jars have same name, but jars are different for different versions of code.
    I want to execute the same code but with different jars on run time.
    Once the jar is loaded for one version, i want to unload it and then load the new jar for new version.
    Can we do this?

    Thanks

  86. you have an entry as (package, classname, classloader). Therefore the same class can be loaded twice by two different ClassLoader instances.

    1- how is it possible to make two class with same name in same package?
    2- can you give provide a example where you are loading same class with two class loader?
    3. how to know JVM which classloader class need to used?

  87. Nice article, but I wish there is bit more information.

  88. Hi,
    I’m working on that batch application development. currently i’m developing Connection Pool using C3p0. i want to create one object for connection pooling to entire batch. how to load the connection pool class only once in jvm.

    Thanks and Regards,
    Manoj Kumar A

  89. Joe, What About the classloading process in OSGi? How does it happen?

  90. Nice Article. Now I understand class loader. I also have query on what’s the maximum number of frame in java stack? is there any maximum number of frames or frame size in java stack?

    Surya

  91. Pingback: Java Instrumentation

  92. As you mentioned in your blog, classes are loaded at runtime. But when i see a verbose of the class with small Hello.java as example, the required classes like Object, String, System etc.. are loaded at compile time… Please correct me if am wrong… Please explain…

    Example: Here Verbose says, it is loading.. it means not still loaded…

    [loading ZipFileIndexFileObject[C:\Program Files\Java\jdk1.7.0_25\lib\ct.sym(MET
    A-INF/sym/rt.jar/java/io/OutputStream.class)]]

    c:\>javac -verbose c:\temp\Hello.java
    [parsing started RegularFileObject]
    [parsing completed 32ms]
    [search path for source files: .]
    [search path for class files: C:\Program Files\Java\jdk1.7.0_25\jre\lib\resource
    s.jar,C:\Program Files\Java\jdk1.7.0_25\jre\lib\rt.jar,C:\Program Files\Java\jdk
    1.7.0_25\jre\lib\sunrsasign.jar,C:\Program Files\Java\jdk1.7.0_25\jre\lib\jsse.j
    ar,C:\Program Files\Java\jdk1.7.0_25\jre\lib\jce.jar,C:\Program Files\Java\jdk1.
    7.0_25\jre\lib\charsets.jar,C:\Program Files\Java\jdk1.7.0_25\jre\lib\jfr.jar,C:
    \Program Files\Java\jdk1.7.0_25\jre\classes,C:\Program Files\Java\jdk1.7.0_25\jr
    e\lib\ext\access-bridge-64.jar,C:\Program Files\Java\jdk1.7.0_25\jre\lib\ext\dns
    ns.jar,C:\Program Files\Java\jdk1.7.0_25\jre\lib\ext\jaccess.jar,C:\Program File
    s\Java\jdk1.7.0_25\jre\lib\ext\localedata.jar,C:\Program Files\Java\jdk1.7.0_25\
    jre\lib\ext\sunec.jar,C:\Program Files\Java\jdk1.7.0_25\jre\lib\ext\sunjce_provi
    der.jar,C:\Program Files\Java\jdk1.7.0_25\jre\lib\ext\sunmscapi.jar,C:\Program F
    iles\Java\jdk1.7.0_25\jre\lib\ext\zipfs.jar,.]
    [loading ZipFileIndexFileObject[C:\Program Files\Java\jdk1.7.0_25\lib\ct.sym(MET
    A-INF/sym/rt.jar/java/lang/Object.class)]]
    [loading ZipFileIndexFileObject[C:\Program Files\Java\jdk1.7.0_25\lib\ct.sym(MET
    A-INF/sym/rt.jar/java/lang/String.class)]]
    [checking Hello]
    [loading ZipFileIndexFileObject[C:\Program Files\Java\jdk1.7.0_25\lib\ct.sym(MET
    A-INF/sym/rt.jar/java/lang/AutoCloseable.class)]]
    [loading ZipFileIndexFileObject[C:\Program Files\Java\jdk1.7.0_25\lib\ct.sym(MET
    A-INF/sym/rt.jar/java/lang/System.class)]]
    [loading ZipFileIndexFileObject[C:\Program Files\Java\jdk1.7.0_25\lib\ct.sym(MET
    A-INF/sym/rt.jar/java/io/PrintStream.class)]]
    [loading ZipFileIndexFileObject[C:\Program Files\Java\jdk1.7.0_25\lib\ct.sym(MET
    A-INF/sym/rt.jar/java/io/FilterOutputStream.class)]]
    [loading ZipFileIndexFileObject[C:\Program Files\Java\jdk1.7.0_25\lib\ct.sym(MET
    A-INF/sym/rt.jar/java/io/OutputStream.class)]]
    [wrote RegularFileObject]
    [total 642ms]

  93. Hi Joe,
    This is very good informative classloaders concept. Thanks for providing this concept.

    Regards,
    Lucky :).

  94. Its very simple n short explanation awesome Joe keep it up.

  95. Joe this UI look is not convenient to read but before UI excellent

  96. Hi Joe,

    I red so many articles of you, for every reader reads only if his/her eye is comfortable to see the font or anything in the page then only he will read and this is my suggestion only if possible change UI look like before, once again i am saying before UI look is very good and your scenario related images also

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>