Java Colombo Meetup
January 16th, 2014

Java Class Loading:
Tips and Tricks
Sameera Jayasoma
Software Architect
WSO2
Java Objects

http://docs.oracle.com/javase/tutorial/java/concepts/object.html

Java objects consist of state and behaviou...
Car myCar = new Car();

myCar is an object of the class Car.
Bytecodes of the class Car is stored at Car.class file.
Class myCarClass = myCar.getClass()

Now what is myCarClass?
Class myCarClass = myCar.getClass()

A Class object is an instance of the java.lang.Class.
It is used to describe a class ...
Java Application
● Can be considered as a set of classes.
○ These classes are called user-defined classes
○ Classpath para...
Java Virtual Machine
http://en.wikipedia.org/wiki/Java_virtual_machine

● A virtual machine which can
execute java bytecod...
What is Classloading?
● Loading classes (Java bytecode) into the JVM.
● Simple Java applications can use the built-in clas...
(Q) Why should I worry about class loading and
ClassLoaders?
(Q) Can I simply survive with the built-in class loading
faci...
Agenda
Basics of Java class loading <-Custom ClassLoaders
Common class loading problems: Diagnosing and resolving
them.
J2...
Java Class Loading
● .class file
○ Smallest unit that gets loaded by the ClassLoader.
○ Contains executable bytecodes and ...
Java Class Loading..

java -classpath C:my-java-app.jar org.sample.Main

● JVM loads Main class and other referenced class...
Java Class Loading..
● Explicit class loading.
○ How a developer writes code to load a class.
○ e.g. Loading an implementa...
Phases of Class Loading
Three phase of class loading: Physical loading, linking
and initializing.
Java ClassLoaders
● Responsible for loading
classes.
● Instances of java.lang.
ClassLoader class.
● Usually arranged in a
...
Java ClassLoaders..
● Initiating ClassLoader
○ ClassLoader that received the initial request to the
load the class
● Defin...
Java ClassLoaders..
● Uses unique namespaces per ClassLoader
○ Class name of the ClassLoader.
○ Loads a class only once.
○...
Features of ClassLoaders
1) Hierarchical Structure: Class loaders in Java are organized
into a hierarchy with a parent-chi...
Features of ClassLoaders..
2) Delegation mode:
○ A class loading request is delegate between classloaders.
This delegation...
Features of ClassLoaders..
2) Delegation mode:
● Default is the parentfirst mode.

http://patentimages.storage.googleapis....
Features of ClassLoaders..
3) Visibility limit:
● A child class loader can find the class in the parent class
loader;
● ho...
Agenda
Basics of Java class loading.
Custom ClassLoaders <-Common class loading problems: Diagnosing and resolving
them.
J...
Custom ClassLoaders
● Through a custom ClassLoader, a programmer can
customize the class loading behaviour.
● Custom Class...
Java 2 ClassLoader API
public abstract class ClassLoader extends Object {
protected ClassLoader(ClassLoader parent);
// Co...
URLClassLoader
● Load classes and resources from a search path of
URLs referring to both JAR files and directories.
○ Any ...
Creating a Custom ClassLoader
public class loadClass(String name) throws ClassNotFoundException {
// Check whether the cla...
Applications of ClassLoaders
● Hot deployment of code
○

updating running software w/o a restart

● Modifying class files
...
Agenda
Basics of Java class loading
Custom ClassLoaders
Common class loading problems: Diagnosing and
resolving them. <-J2...
Retrieving Class Loading Info.
> Thread.currentThread().getContextClassLoader();
> this.getClass().getClassLoader();
> Cla...
ClassNotFoundException
Occurs when the following conditions exists.
● The class is not visible in the logical classpath of...
ClassCastException
Occurs when the following conditions exists.
● The source object is not an instance of the target class...
NoClassDefFoundError
● Class existed at compile time but no longer available in
the runtime.
○ Basically class does not ex...
LinkageErrors

Subclasses:
●
●
●
●
●

AbstractMethodError
ClassCircularityError
ClassFormatError
NoSuchMethodError
..
Agenda
Basics of Java class loading
Custom ClassLoaders
Common class loading problems: Diagnosing and resolving
them.
J2EE...
Tomcat

http://tomcat.apache.org/tomcat-7.0-doc/class-loader-howto.html
JBOSS 4.0.x

http://www.infoq.com/presentations/java-classloading-architectures-ernie-svehla
Agenda
Basics of Java class loading
Custom ClassLoaders
Common class loading problems: Diagnosing and resolving
them.
J2EE...
What is OSGi?
Class loading in OSGi

Classloader
Network.
Delegate each
other for
classloading
requests.
References
● http://www.infoq.com/presentations/java-classloading-architecturesernie-svehla
● http://www2.sys-con.
com/its...
http://www.smileysymbol.com/2012/05/smiley-face-collection-10-pics.html

Thank You!!!
Java class loading  tips and tricks - Java Colombo Meetup, January, 2014
Java class loading  tips and tricks - Java Colombo Meetup, January, 2014
Java class loading  tips and tricks - Java Colombo Meetup, January, 2014
Java class loading  tips and tricks - Java Colombo Meetup, January, 2014
Upcoming SlideShare
Loading in...5
×

Java class loading tips and tricks - Java Colombo Meetup, January, 2014

3,873

Published on

Published in: Technology, Education

Java class loading tips and tricks - Java Colombo Meetup, January, 2014

  1. 1. Java Colombo Meetup January 16th, 2014 Java Class Loading: Tips and Tricks Sameera Jayasoma Software Architect WSO2
  2. 2. Java Objects http://docs.oracle.com/javase/tutorial/java/concepts/object.html Java objects consist of state and behaviour just like any real-world object.
  3. 3. Car myCar = new Car(); myCar is an object of the class Car. Bytecodes of the class Car is stored at Car.class file.
  4. 4. Class myCarClass = myCar.getClass() Now what is myCarClass?
  5. 5. Class myCarClass = myCar.getClass() A Class object is an instance of the java.lang.Class. It is used to describe a class of a Java object.
  6. 6. Java Application ● Can be considered as a set of classes. ○ These classes are called user-defined classes ○ Classpath parameter tells the Java Virtual Machine (JVM) or the Java compiler where to look for these user-defined classes. java -classpath C:my-java-app.jar org.sample.Main
  7. 7. Java Virtual Machine http://en.wikipedia.org/wiki/Java_virtual_machine ● A virtual machine which can execute java bytecode. ● JVM is responsible for loading and executing code/classes on the Java platform. ● JVM loads these code/classes only when they are required. (lazy loading of classes)
  8. 8. What is Classloading? ● Loading classes (Java bytecode) into the JVM. ● Simple Java applications can use the built-in class loading facility. ● More complex applications usually defines custom class loading mechanisms. ● JVM uses an entity called ClassLoader to load classes.
  9. 9. (Q) Why should I worry about class loading and ClassLoaders? (Q) Can I simply survive with the built-in class loading facility in Java? http://alyerks.blogspot.com
  10. 10. Agenda Basics of Java class loading <-Custom ClassLoaders Common class loading problems: Diagnosing and resolving them. J2EE class loading architectures Classloading in OSGi
  11. 11. Java Class Loading ● .class file ○ Smallest unit that gets loaded by the ClassLoader. ○ Contains executable bytecodes and links to dependent classes. ○ CL reads the bytecodes and create java.lang.Class instance. ○ When JVM starts, only the main class is loaded, other classes are loaded lazily. ○ This behaviour allows the dynamic extensibility of the Java platform.
  12. 12. Java Class Loading.. java -classpath C:my-java-app.jar org.sample.Main ● JVM loads Main class and other referenced classes implicitly by using default ClassLoaders available in Java. ○ I.e Developer do not need to write code to load classes.
  13. 13. Java Class Loading.. ● Explicit class loading. ○ How a developer writes code to load a class. ○ e.g. Loading an implementation of the Car interface. // Create a Class instance of the MazdaAxela class. Class clazz = Class.forName(“org.cars.MazdaAxela”); // Creates an instance of the Car. Car mzAxela = (Car) clazz.newInstance();
  14. 14. Phases of Class Loading Three phase of class loading: Physical loading, linking and initializing.
  15. 15. Java ClassLoaders ● Responsible for loading classes. ● Instances of java.lang. ClassLoader class. ● Usually arranged in a hierarchical manner with a parent-child relationship. ● Every classloader has a parent classloader except for the Bootstrap classloader. http://www.cubrid.org/blog/dev-platform/understanding-jvm-internals/
  16. 16. Java ClassLoaders.. ● Initiating ClassLoader ○ ClassLoader that received the initial request to the load the class ● Defining ClassLoader ○ ClassLoader that actually loads the class.
  17. 17. Java ClassLoaders.. ● Uses unique namespaces per ClassLoader ○ Class name of the ClassLoader. ○ Loads a class only once. ○ Same class loaded by two different class loaders are not compatible with each. ■ ClassCastExceptions can occur.
  18. 18. Features of ClassLoaders 1) Hierarchical Structure: Class loaders in Java are organized into a hierarchy with a parent-child relationship. The Bootstrap Class Loader is the parent of all class loaders. http://imtiger.net/blog/2009/11/09/java-classloader/
  19. 19. Features of ClassLoaders.. 2) Delegation mode: ○ A class loading request is delegate between classloaders. This delegation is based on the hierarchical structure. ○ In parent-first delegation mode, the class loading request is delegated to the parent to determine whether or not the class is in the parent class loader. ○ If the parent class loader has the class, the class is used. ○ If not, the class loader requested for loading loads the class.
  20. 20. Features of ClassLoaders.. 2) Delegation mode: ● Default is the parentfirst mode. http://patentimages.storage.googleapis.com/US7603666B2/US07603666-20091013D00002.png
  21. 21. Features of ClassLoaders.. 3) Visibility limit: ● A child class loader can find the class in the parent class loader; ● however, a parent class loader cannot find the class in the child class loader. 4) Unload is not allowed: ● A class loader can load a class but cannot unload it. ● Instead of unloading, the current class loader can be deleted, and a new class loader can be created.
  22. 22. Agenda Basics of Java class loading. Custom ClassLoaders <-Common class loading problems: Diagnosing and resolving them. J2EE class loading architectures Classloading in OSGi
  23. 23. Custom ClassLoaders ● Through a custom ClassLoader, a programmer can customize the class loading behaviour. ● Custom ClassLoaders are implemented by extending java.lang.ClassLoader abstract class. ● Common approach to creating a custom classloader is to override the loadClass() method in the java.lang. ClassLoader.
  24. 24. Java 2 ClassLoader API public abstract class ClassLoader extends Object { protected ClassLoader(ClassLoader parent); // Converts an array of bytes into an instance of class protected final Class defineClass(String name,byte[] b,int off,int len) throws ClassFormatError; // Finds the class with the specified binary name. protected Class findClass(String className) throws ClassNotFoundException; // Returns the class with the name, if it has already been loaded. protected final Class findLoadedClass(String name); // Loads the class with the specified binary name. public class loadClass(String className) throws ClassNotFoundException; }
  25. 25. URLClassLoader ● Load classes and resources from a search path of URLs referring to both JAR files and directories. ○ Any URL that ends with a '/' is assumed to refer to a directory. ○ Otherwise, the URL is assumed to refer to a JAR file which will be opened as needed.
  26. 26. Creating a Custom ClassLoader public class loadClass(String name) throws ClassNotFoundException { // Check whether the class is already loaded Class c = findLoadedClass(name); if( c == null) { try { // Delegation happens here c.getParent().loadClass(name) } catch (ClassNotFoundException e) { // Ignored } if (c == null) { // Load the class from the local repositories c = findClass(name); } } return c; }
  27. 27. Applications of ClassLoaders ● Hot deployment of code ○ updating running software w/o a restart ● Modifying class files ○ to inject extra debugging information. ● Classloaders and security. ○ ○ ○ Classloaders define namespaces for the classes loaded by them. A class is uniquely identified by the package name and the classloader. Different trust levels can be assigned to namespaces defined by classloaders.
  28. 28. Agenda Basics of Java class loading Custom ClassLoaders Common class loading problems: Diagnosing and resolving them. <-J2EE class loading architectures Classloading in OSGi
  29. 29. Retrieving Class Loading Info. > Thread.currentThread().getContextClassLoader(); > this.getClass().getClassLoader(); > ClassLoader.getParent(); > Class.getClassLoader(); JVM Tools -verbose - argument gives you a comprehensive output of the class loading process.
  30. 30. ClassNotFoundException Occurs when the following conditions exists. ● The class is not visible in the logical classpath of the classloader. ○ Reference to the class is too high in the class loading hierarchy ● The application incorrectly uses a class loader API ● A dependent class is not visible.
  31. 31. ClassCastException Occurs when the following conditions exists. ● The source object is not an instance of the target class. Car myCar = (Car) myDog ● The classloader that loaded the source class is different from the classloader that loaded the target class. Car myCar = (Car) yourCar
  32. 32. NoClassDefFoundError ● Class existed at compile time but no longer available in the runtime. ○ Basically class does not exist in the logical class path. ● The class cannot be loaded. This can occur due to various reasons. ○ failure to load the dependent class, ○ the dependent class has a bad format, ○ or the version number of a class.
  33. 33. LinkageErrors Subclasses: ● ● ● ● ● AbstractMethodError ClassCircularityError ClassFormatError NoSuchMethodError ..
  34. 34. Agenda Basics of Java class loading Custom ClassLoaders Common class loading problems: Diagnosing and resolving them. J2EE class loading architectures <-Classloading in OSGi
  35. 35. Tomcat http://tomcat.apache.org/tomcat-7.0-doc/class-loader-howto.html
  36. 36. JBOSS 4.0.x http://www.infoq.com/presentations/java-classloading-architectures-ernie-svehla
  37. 37. Agenda Basics of Java class loading Custom ClassLoaders Common class loading problems: Diagnosing and resolving them. J2EE class loading architectures Classloading in OSGi <--
  38. 38. What is OSGi?
  39. 39. Class loading in OSGi Classloader Network. Delegate each other for classloading requests.
  40. 40. References ● http://www.infoq.com/presentations/java-classloading-architecturesernie-svehla ● http://www2.sys-con. com/itsg/virtualcd/java/archives/0808/chaudhri/index.html ● http://www.techjava.de/topics/2008/01/java-class-loading/
  41. 41. http://www.smileysymbol.com/2012/05/smiley-face-collection-10-pics.html Thank You!!!
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×