Java Class Loader

Last modified on September 7th, 2014 by Joe.

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:

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;

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.

Comments on "Java Class Loader"

  1. Chendra says:

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

  2. shubham says:

    good explanation joe….thanks

  3. Anonymous says:

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

  4. Prabhakar says:

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

  5. Dhana says:

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

  6. Anonymous says:

    Thanx for loading this article…

  7. Aishwarya says:

    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.

  8. Karan says:

    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

  9. Rao says:

    Following is not clear:

    “Extensions Class Loader”

    Pl give examples of some existing extensions.

    Rao

  10. Ram says:

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

  11. Abirami says:

    Nice Article……

  12. Irina says:

    Thank you! I love all of your posts!

  13. steven says:

    Thanks a ton.

  14. Bhushan says:

    Good Article . Liked

  15. Joe says:

    @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

  16. GeekDude says:

    Nice one..

  17. Anonymous says:

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

  18. vikas ohlyan says:

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

  19. Kumar says:

    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.

  20. Anonymous says:

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

  21. Tuhin says:

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

  22. Karan says:

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

  23. Anonymous says:

    Good one joe. Thaks a lot.

  24. Anonymous says:

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

  25. sasikanth says:

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

  26. Aashu says:

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

  27. Anonymous says:

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

  28. srishti says:

    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 :)

  29. sun-soft says:

    its up to marks.Gorgeous

  30. ram says:

    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.

  31. Anonymous says:

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

  32. Hemant Chaudhary says:

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

  33. Gireesh Mandhale says:

    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!

  34. Joe says:

    Thanks Gireesh, fixed it.

  35. uma says:

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

  36. swarna says:

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

  37. chhatrapal says:

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

  38. chhatrapal says:

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

  39. chhatrapal says:

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

  40. arivoli says:

    Nice article….

  41. wes says:

    This was great. Love your site. Thanks

  42. Mohd Javed says:

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

  43. rohit says:

    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 .

  44. Anonymous says:

    Good post

  45. GN says:

    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

  46. Indraneel says:

    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

  47. Josiah says:

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

  48. Ramraj says:

    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!

  49. Madhavi says:

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

  50. sachin kashyap says:

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

  51. Audiseshu says:

    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

  52. Sridhar.Goranti says:

    Nice explanation and it is useful for all that in very simple manner, Expecting more for the same.

  53. Shri says:

    good

  54. Anonymous says:

    Hi Joe,

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

  55. Vinoth Sampath says:

    Hi Joe,

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

  56. Koustav says:

    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) ?

  57. sailu says:

    such a good article ….thank you Joe sir.

  58. Avinash Anand says:

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

  59. shekhar says:

    hey awesome information….thanks for the post

  60. sree says:

    u r awesome

  61. Anonymous says:

    really helpful

  62. Y.Jayaram Reddy says:

    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.

  63. Deepak says:

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

    nice work…thanx :)

  64. milin modi says:

    Its really good thing abt class loader thanx joe

  65. Gobi says:

    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.

  66. Shivkant Pandey says:

    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

  67. maddy says:

    nice article Joe

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

  68. pankaj mangal says:

    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.

  69. sumit says:

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

    please its urgent………..

  70. sujith says:

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

  71. frufru says:

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

  72. Kavindra says:

    This explanation is very… best
    Thanks JOE Sir

  73. Kavindra says:

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

  74. Archana says:

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

  75. Joe says:

    Thanks.
    Already I have started writing on Spring. https://javapapers.com/category/spring/

    Hibernate coming soon!

    Struts will take some time.

  76. Anonymous says:

    very informative thanks alot

  77. Bhavin says:

    it’s very good artical about class loader…

  78. kamesh says:

    excellent

  79. unni says:

    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 !

  80. Shahzadah Babu says:

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

  81. Sadeshkumar Periyasamy says:

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

  82. Sadeshkumar Periyasamy says:

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

  83. Gaurav Gupta says:

    Nice article…

    Thanks

  84. Jayesh Anil Pawar says:

    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?

  85. RANGA REDDY JULAKANTI says:

    very nice article

  86. RANGA REDDY JULAKANTI says:

    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.

  87. Manish says:

    Hai you can go through this link of JAVA API and get all details of classLoaders.

  88. jagan says:

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

  89. Manuel Miranda says:

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

  90. kamal says:

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

  91. Manish Kumar Jha says:

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

  92. balaji says:

    Really great post

  93. Anonymous says:

    good tutorials

  94. guru says:

    good work

  95. […] is not required and all the all divers found in classpath are loaded automatically. When we want to load a java class into JVM we use Class.forName and the same is followed here. We choose a type of JDBC driver and use […]

  96. Anonymous says:

    This is Mahesh

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

  97. Hari says:

    Nice sir..

  98. Pramod says:

    Great..

  99. Shishupal Shakya says:

    Excellent

  100. chiranjeevi says:

    hi joe,

    your explanation is simple and getting more information about class loaders etc.,

    thanks joe

  101. suresh says:

    hi joe you said simple but moreinfermation getting

  102. Anonymous says:

    I

  103. Anonymous says:

    I want

  104. Riju says:

    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

  105. Anonymous says:

    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?

  106. Manoj Kumar says:

    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

  107. Mahesh says:

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

  108. HariKrishna says:

    Hi
    Joe

    You explanation is simply superb.
    I catch it very Simple

    Thanks
    HariKrishna

  109. perumal says:

    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

  110. […] means. For example using Java instrumentation, we can access a class that is loaded by the Java classloader from the JVM and modify its bytecode by inserting our custom code, all these done at runtime. […]

  111. Anonymous says:

    Nice article Jeo

  112. vijay says:

    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[c language=”: empHello.java”][/c]]
    [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[c language=”: empHello.class”][/c]]
    [total 642ms]

  113. Lucky says:

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

    Regards,
    Lucky :).

  114. sachin says:

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

  115. Veerendra says:

    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

  116. kumar says:

    Nicely present and simply put in words. Really nice work.

  117. Hikmat Dhamee says:

    I really appreciate this tutorial…Really helpful!!!

  118. Hikmat Dhamee says:

    Would you think also about writing such tutorial on Resource Loading in Java

  119. ranendra says:

    Hi Joe well explanation…i have a single doubt :
    can anybody tell me how does JVM decide which class to be loaded first in our application?

Comments are closed for "Java Class Loader".