Pages

How Java Class is loaded into JVM


How Java Class is loaded into JVM


Java ClassLoader loads the classes at runtime. Class Loader in java works on three principle: Delegation, Visibility and Uniqueness .

1. Delegation: Delegation forward the incoming request of a class loading to a parent ClassLoader and only loads the class.

2. Visibility : Visibility allows child ClassLoader to see or check whether all classes is loaded by the parent ClassLoader but parent  ClassLoader can not check whether all classes loaded by the child ClassLoader.

3. Uniqueness: uniqueness allows to load a class exactly once. Which is basically achieved by the delegation and ensure that child ClassLoader doesn’t reload the class already loaded by the parent.

Note : One java class couldn’t loaded by two different ClassLoader.

ClassLoader in Java is a class which is used to load the class files in java. Java code is complied using javac complier and JVM executes the java program by running the byte code from the class file. ClassLoader is responsible to load the class from the file system, network or any other sources.

There are three type of ClassLoader in java and every ClassLoader has predefined location from where they loads the classes. 

      1.  BootStrap ClassLoader  Or Primordial ClassLoader  (JRE/lib/rt.jar)
      2.  Extension ClassLoader  (JRE/lib/ext or any directory denoted by java.ext.dirs)
      3. Application ClassLoader  (ClassPath, environment variable, -classpath, -cp option, ClassPath attribute                             in Manifest inside a JAR)







BootStrap ClassLoader is parent of all the ClassLoader in java, If you call String.class.getClassLoader() it will return null. Extension ClassLoader delegates request to parent ClassLoader (Bootstrap), If it fails to find the class than Extension ClassLoader loads the class from JRE/lib/ext or JRE/ext/dirs (System Property). Extension ClassLoader in JVM is implemented by sun.misc.Launcher$ExtClassLoader

Third default ClassLoader  used by JVM is System or Application ClassLoader. It loads the classes from classpath, -cp command line option, Class-Path attribute of Manifest file inside JAR
Application ClassLoader is the child of Extension ClassLoader and implemented by sun.misc.Launcher$AppClassLoader class. Bootstrap ClassLoader is basically implemented in native language like C. All java class loaders are implemented  using java.lang.ClassLoader.






Delegation Principles : A class is loaded in java when it needs or requires. Suppose you have an application specific class called Employee.class, first request of loading this class will come to Application ClassLoader which will delegates request to Extension ClassLoader which further delegates it to Bootstrap ClassLoader. Bootstrap or Primordial ClassLoader will check this class in JRE/lib/rt.jar and since this class is not there, request comes to Extension ClassLoader which looks this class in JRE/lib/ext or JRE/ext/dirs directory and tries to locate this class there. If class is found there than Extension ClassLoader will load that class and Application ClassLoader will never load this class But if its not loaded by Extension ClassLoader than Application ClassLoader load this class from classpath in java.

Note: classpath is used to load  class files while PATH is used to executable like javac or java command.

Visibility Prinicples : Child ClassLoader can see or check classes loaded by parent ClassLoader but it’s vice versa not true. Which mean if Employee class is loaded by Application ClassLoader than trying to load this class explicly using Extension ClassLoader will throw java.lang.ClassNotFoundException.

Uniqueness Principles : According to this principle a class loaded by Parent should not be loaded by Child ClassLoader again. Though its completely possible to write class loader which violates Delegation and Uniqueness principles and loads class by itself, its not something which is beneficial. You should follow all  class loader principle while writing your own ClassLoader.


How to load class explicitly in java :

Java provides API to explicitly load a class by Class.forName(classname) and Class.forName(classname, initialized, classloader),  As shown in below example you can pass name of ClassLoader which should be used to load that particular class along with binary name of class. Class is loaded by calling loadClass() method of java.lang.ClassLoader class which calls findClass() method to locate bytecodes for corresponding class. In this example Extension ClassLoader uses java.net.URLClassLoader which search for class files and resources in JAR and directories. any search path which is ended using "/" is considered directory. If findClass() does not found the class than it throws java.lang.ClassNotFoundException and if it finds it calls defineClass() to convert bytecodes into a .class instance which is returned to the caller.


Where to use ClassLoader in Java :

ClassLoader in Java is a powerful concept and used at many places. One of the popular example of ClassLoader is AppletClassLoader which is used to load class by Applet, since Applets are mostly loaded from internet rather than local file system, By using separate ClassLoader you can also loads same class from multiple sources and they will be treated as different class in JVM. J2EE uses multiple class loaders to load class from different location like classes from WAR file will be loaded by Web-app ClassLoader while classes bundled in EJB-JAR is loaded by another class loader. Some web server also supports hot deploy functionality which is implemented using ClassLoader. You can also use ClassLoader to load classes from database or any other persistent store.

import java.util.logging.Level;
import 
java.util.logging.Logger;

/**
 * Java program that define How ClassLoader works in Java,
 * in particular about visibility principle of ClassLoader.
 *
 * @author Anuj Verma
 */


public class ClassLoaderTest 
{

    public static 
void main(String args[]) {
        try 
{       
            
//printing ClassLoader of this class
            System.
out.println("ClassLoaderTest.getClass().getClassLoader() : "
                                 + ClassLoaderTest.class.getClassLoader());


       
            
//trying to explicitly load this class again using Extension class loader
            Class.
forName("test.ClassLoaderTest"true 
                            ,  ClassLoaderTest.class.getClassLoader().getParent());

        
} catch (ClassNotFoundException ex) {
            Logger.
getLogger(ClassLoaderTest.class.getName()).log(Level.SEVEREnull, ex);
        
}
    
}

}

Output:
ClassLoaderTest.
getClass().getClassLoader() : sun.misc.Launcher$AppClassLoader@601bb1
16/08/2012 2:43:48 AM test.ClassLoaderTest
 main
SEVERE: 
null
java.
lang.ClassNotFoundException: test.ClassLoaderTest
        at java.
net.URLClassLoader$1.run(URLClassLoader.java:202)
        at java.
security.AccessController.doPrivileged(Native Method)
        at java.
net.URLClassLoader.findClass(URLClassLoader.java:190)
        at sun.
misc.Launcher$ExtClassLoader.findClass(Launcher.java:229)
        at java.
lang.ClassLoader.loadClass(ClassLoader.java:306)
        at java.
lang.ClassLoader.loadClass(ClassLoader.java:247)
        at java.
lang.Class.forName0(Native Method)
        at java.
lang.Class.forName(Class.java:247)
        at test.
ClassLoaderTest.main(ClassLoaderTest.java:29)



85 comments:

  1. wow....Thanks for sharing this great source full of SOAP UI related posts.realy great work onece again thanks me and leadonlinetraining.

    ReplyDelete
  2. it's a wonderful blog. this blog consisting of very nice information..plz once visit the link you gain more knowledge...HIBERNATE ONLINE TRAINING .

    ReplyDelete
  3. Nice Blog.....
    Thanks for sharing such a good information...
    We offer HIBERNATE ONLINE TRAINING

    ReplyDelete
  4. Nice Blog.....
    Thanks for sharing such a good information...
    We offer HIBERNATE ONLINE TRAINING

    ReplyDelete
  5. Java is the most robust secured and multi threaded programming language which is the reason why most the the developers go for java. A single java code can be used for various platforms.
    JAVA training in chennai | java training institutes in chennai | FITA Academy Chennai

    ReplyDelete
  6. unix training in chennai
    Very informative piece of article, this blog has helped me to understand the concept even better. Keep on blogging.

    ReplyDelete
  7. This is a great article, I have been always to read something with specific tips! I will have to work on the time for scheduling my learning.
    Selenium Training in Chennai

    ReplyDelete


  8. Welcome Post very usefull informatation.and iam expecting more post like this please keep updating us........

    ReplyDelete
  9. Thanks for splitting your comprehension with us. It’s really useful to me & I hope it

    helps the people who in need of this vital information.
    The

    Best Hibernate Training in Tambaram
    Chennai | Hibernate Training institutes in

    Chennai

    ReplyDelete
  10. Thanks for splitting your comprehension with us. It’s really useful to me & I hope it helps he people who in need of this vital informationAJAX Training in Tambaram

    ReplyDelete
  11. Thanks for splitting your comprehension with us. It’s really useful to me & I hope it helps he people who in need of this vital informationHibernate Training in Tambaram

    ReplyDelete
  12. Thanks for the explanation. It’s really helpful .Thanks you. Please keep sharing
    Hibernate training in Delhi

    ReplyDelete
  13. Nice post .Really appreciable. Please share more information. Thanks you
    Hibernate Institute in Noida

    ReplyDelete

  14. Thanks for sharing this Information. This content is so informative and helpful for many people.
    Hibernate Training in Gurgaon

    ReplyDelete
  15. Thanks for splitting your comprehension with us. It’s really useful to me & I hope it helps the people who in need of this vital information. 
    AWS training in Chennai
    selenium training in Chennai

    ReplyDelete
  16. I am commenting to let you know what a terrific experience my daughter enjoyed reading through your web page. She noticed a wide variety of pieces, with the inclusion of what it is like to have an awesome helping style to have the rest without hassle grasp some grueling matters.


    ccna training in chennai



    ccna training in bangalore


    ccna training in pune

    ReplyDelete
  17. Thank you for benefiting from time to focus on this kind of, I feel firmly about it and also really like comprehending far more with this particular subject matter. In case doable, when you get know-how, is it possible to thoughts modernizing your site together with far more details? It’s extremely useful to me.
    java training in chennai | java training in bangalore

    java training in tambaram | java training in velachery

    java training in omr

    ReplyDelete
  18. Great post. Needed to write simple word that Thanks for suggestions. Keep it up! best sap simple finance online training institute in hyderabad

    ReplyDelete
  19. I read this post two times, I like it so much, please try to keep posting & Let me introduce other material that may be good for our community.
    python training in chennai
    python training in Bangalore
    Python training institute in chennai

    ReplyDelete
  20. Microsoft Dynamics CRM Course Overview

    Microsoft Dynamics CRM training online courses Microsoft Dynamics CRM Training Online

    is a competent and experienced Customer Relationship Management bundle. As demonstrated by Microsoft, Customer Relationship Management passes on a widely inclusive point of view of each customer that enables client standing up to delegates to settle on accelerated and compromise about indispensable attempts in the business, publicizing, and customer organization fields.

    Your adequacy in dealing with your client relationships utilizing CRM is specifically identified with your level of authority of the application. New Horizons gives preparing to empower you to manufacture your expertise set and get the most out of this phenomenal apparatus.

    It is customer relationship management training and then MDC –CRM is taking care of the full satisfaction of the customer and loyalty of the other business improvement. In an additional, it helps the business expansion and the why that the Microsoft Dynamics is very specialization and why is always getting the great demand over the field of the business. Therefore our company conducts the online training with the experience staffs that have high skill and updated talent in the current field. Most of the students have enough time so they can attend the regular class but the job professional, don’t have sufficient time so they look for the online Microsoft Dynamics CRM Training to allocate the session per the time of them.

    On the day the candidate who completes the course can receive certification that assist for the student to attend the major job. They allocated the project assignment for each candidate so student can gain more practical skill on this training so you easy to meet any kind of the interviews and handle the major new project by own.

    ReplyDelete
  21. This comment has been removed by the author.

    ReplyDelete
  22. I appreciate your efforts because it conveys the message of what you are trying to say. It's a great skill to make even the person who doesn't know about the subject could able to understand the subject . Your blogs are understandable and also elaborately described. I hope to read more and more interesting articles from your blog. All the best.
    Data Science course in kalyan nagar | Data Science Course in Bangalore | Data Science course in OMR | Data Science Course in Chennai

    Data Science course in chennai | Best Data Science training in chennai | Data science course in velachery | Data Science course in Chennai

    Data science course in jaya nagar | Data Science course in Bangalore | Data science training in tambaram | Data Science Course in Chennai

    ReplyDelete
  23. Superb. I really enjoyed very much with this article here. Really it is an amazing article I had ever read. I hope it will help a lot for all. Thank you so much for this amazing posts and please keep update like this excellent article. thank you for sharing such a great blog with us.
    online Python training | python training in chennai

    ReplyDelete
  24. It is amazing and wonderful to visit your site.Thanks for sharing this information,this is useful to me...
    Micromax led tv repair

    ReplyDelete
  25. Thank you so much for your information,its very useful and helful to me.Keep updating and sharing. Thank you.
    Bouncers for hire in chennai |
    Bouncers service in aynavaram

    ReplyDelete
  26. Thanks for your post. This is excellent information. The list of your blogs is very helpful for those who want to learn, It is amazing!!! You have been helping many application.
    Fruits and Vegetable Rack in Chennai |

    Supermarket rack in Chennai |

    Trolley Manufacture In Chennai |

    ReplyDelete
  27. your information is really awesome as well as it is very excellent and i got more interesting information from your blog...
    HD camera Installation in chennai |

    IP Camera in chennai |

    Biometric attendance in chennai

    ReplyDelete
  28. Really nice experience you have. Thank you for sharing. It will surely be an experience to someone.
    Python Online training
    python Training in Chennai
    Python training in Bangalore

    ReplyDelete
  29. Thanks For Sharing Your Information Please Keep Updating Us Time Just Went on Reading the Article Java Course In Hyderabad

    ReplyDelete
  30. My blog goes over a lot of the same topics as yours, and I believe we could greatly benefit from each other. If you happen to be interested, feel free to shoot me an e-mail. I look forward to hearing from you! Great blog by the way!
    industrial safety course in chennai

    ReplyDelete
  31. It's interesting that many of the bloggers to helped clarify a few things for me as well as giving.Most of ideas can be nice content.The people to give them a good shake to get your point and across the command

    Data Science course in Chennai
    Data science course in bangalore
    Data science course in pune
    Data science online course
    Data Science Interview questions and answers
    Data Science Tutorial
    Data science course in bangalore

    ReplyDelete
  32. I‘d mention that most of us visitors are endowed to exist in a fabulous place with very many wonderful individuals with very helpful things.
    apple ipad service center in chennai | apple iphone service center in chennai | Apple laptop service center in chennai | apple iphone service center in chennai

    ReplyDelete
  33. A good blog for the people who really needs information about this. Good work keep it up.

    Guest posting sites
    Technology

    ReplyDelete
  34. Nice Post! Thank you for sharing knowledge, it was very good post to update my knowledge and improve my skills. keep blogging.
    Java Training in Electronic City

    ReplyDelete
  35. This is very great thinks. It was very comprehensive post and powerful concept. Thanks for your sharing with us. Keep it up..
    Oracle Training in Chennai | Oracle Training Institutes in Chennai

    ReplyDelete
  36. Hi, thank you very much for the new information, i learned something new. Very well written. It was sooo good to read and usefull to improve knowledge. Keep posting. If you are looking for any data science related information please visit our website data science course training bangalore.

    ReplyDelete
  37. Very interesting, good job and thanks for sharing such a good blog. your article is so convincing that I never stop myself to say something about it. You’re doing a great job. Keep it up…

    Upgrade your career Learn SAP MM Training in Bangalore from industry experts get Complete hands-on Training, Interview preparation, and Job Assistance at Softgen Infotech.

    ReplyDelete
  38. Happy to found this blog. Good Post!. It was so good to read and useful to improve my knowledge as updated one, keep blogging. Hibernate Training in Electronic City
    Java Training in Electronic City

    ReplyDelete
  39. It's wonderful see that The sites are fully filled with Informative Articles...Good Job!!!Keep it up:)
    Here Some Technical Information's about Java for you "Best Java Training with Placements"
    Java training in chennai | Java training in annanagar | Java training in omr | Java training in porur | Java training in tambaram | Java training in velachery

    ReplyDelete
  40. Your good knowledge and kindness in playing with all the pieces were very useful. I don’t know what I would have done if I had not encountered such a step like this.
    Artificial Intelligence Course
    Java Course
    AWS Course
    Machine Learning Course
    Data Science Course
    DevOps Course

    ReplyDelete
  41. Nice Blog. the blog is really very Impressive. every content of this blog is uniquely represented.keep sharing your information regularly for my future reference. This content creates a new hope and inspiration with me.it was a wonderful chance to visit this kind of site and I am happy to know. thank you so much for giving us a chance to have this opportunity.. This is the exact information I am been searching for, Thanks for sharing the required infos with the clear update and required points.Data Science Training In Chennai

    Data Science Online Training In Chennai

    Data Science Training In Bangalore

    Data Science Training In Hyderabad

    Data Science Training In Coimbatore

    Data Science Training

    Data Science Online Training




    ReplyDelete
  42. Wonderful blog.. Thanks for sharing informative blog.. its very useful to me... oracle training in chennai

    ReplyDelete
  43. Thank you for sharing this useful article with us. This blog is a very helpful to me in future. Keep sharing informative articles with us.

    https://www.ahmedabadcomputereducation.com/course/laravel-training-course/

    ReplyDelete
  44. It is amazing and wonderful to visit your site. Thanks for sharing information; this is useful to us....

    deep learning course in Delhi

    ReplyDelete
  45. Are you having problem in learning new skills or confused to choose between right Passion . So don't worry we are here because our institution is offering CS executive classes and a free of cost CSEET classes. So what are you waiting for contact us or visit our website at https://uniqueacademyforcommerce.com/

    ReplyDelete
  46. If You Are Looking For Forex Broker? Read This Review And Find Out How Much I've Enjoyed My Experience With BITFINEX

    ReplyDelete
  47. Pretty good post. I just stumbled upon your blog and wanted to say that I have really enjoyed reading your blog posts. Any way I’ll be subscribing to your feed and I hope you post again soon. Big thanks for the useful info. data scientist course in surat

    ReplyDelete
  48. This post is very simple to read and appreciate without leaving any details out. Great work!
    data science coaching in hyderabad

    ReplyDelete