SlideShare a Scribd company logo
Java Colombo Meetup
January 16th, 2014

Java Class Loading:
Tips and Tricks
Sameera Jayasoma
Software Architect
WSO2
Java class loading  tips and tricks - Java Colombo Meetup, January, 2014
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.
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 of a Java object.
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
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)
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.
Java class loading  tips and tricks - Java Colombo Meetup, January, 2014
(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
Agenda
Basics of Java class loading <-Custom ClassLoaders
Common class loading problems: Diagnosing and resolving
them.
J2EE class loading architectures
Classloading in OSGi
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.
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.
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();
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
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/
Java ClassLoaders..
● Initiating ClassLoader
○ ClassLoader that received the initial request to the
load the class
● Defining ClassLoader
○ ClassLoader that actually loads the class.
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.
Java class loading  tips and tricks - Java Colombo Meetup, January, 2014
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/
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.
Features of ClassLoaders..
2) Delegation mode:
● Default is the parentfirst mode.

http://patentimages.storage.googleapis.com/US7603666B2/US07603666-20091013D00002.png
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.
Agenda
Basics of Java class loading.
Custom ClassLoaders <-Common class loading problems: Diagnosing and resolving
them.
J2EE class loading architectures
Classloading in OSGi
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.
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;
}
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.
Java class loading  tips and tricks - Java Colombo Meetup, January, 2014
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;
}
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.
Agenda
Basics of Java class loading
Custom ClassLoaders
Common class loading problems: Diagnosing and
resolving them. <-J2EE class loading architectures
Classloading in OSGi
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.
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.
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
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.
LinkageErrors

Subclasses:
●
●
●
●
●

AbstractMethodError
ClassCircularityError
ClassFormatError
NoSuchMethodError
..
Agenda
Basics of Java class loading
Custom ClassLoaders
Common class loading problems: Diagnosing and resolving
them.
J2EE class loading architectures <-Classloading in OSGi
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 class loading architectures
Classloading in OSGi <--
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/itsg/virtualcd/java/archives/0808/chaudhri/index.html
● http://www.techjava.de/topics/2008/01/java-class-loading/
http://www.smileysymbol.com/2012/05/smiley-face-collection-10-pics.html

Thank You!!!

More Related Content

PPTX
Do you really get class loaders?
guestd56374
 
PDF
Understanding ClassLoaders
Martin Skurla
 
DOC
Java Class Loading
Sandeep Verma
 
PPTX
Java class loader
benewu
 
PDF
Java Classloaders
Prateek Jain
 
PPT
Java Class Loader
Bhanu Gopularam
 
PPTX
Let's talk about java class loader
Yongqiang Li
 
PDF
Java Interview Questions Answers Guide
DaisyWatson5
 
Do you really get class loaders?
guestd56374
 
Understanding ClassLoaders
Martin Skurla
 
Java Class Loading
Sandeep Verma
 
Java class loader
benewu
 
Java Classloaders
Prateek Jain
 
Java Class Loader
Bhanu Gopularam
 
Let's talk about java class loader
Yongqiang Li
 
Java Interview Questions Answers Guide
DaisyWatson5
 

What's hot (20)

PPT
Class loader basic
명철 강
 
PDF
Understanding Java Dynamic Proxies
Rafael Luque Leiva
 
PDF
Dynamic Proxy by Java
Kan-Han (John) Lu
 
PDF
55 new things in Java 7 - Devoxx France
David Delabassee
 
PPT
Java Tutorial 1
Tushar Desarda
 
PDF
Advance java kvr -satya
Satya Johnny
 
PDF
Serialization & De-serialization in Java
InnovationM
 
PDF
Basics of java
onewomanmore witl
 
PDF
Smalltalk on the JVM
ESUG
 
PPTX
Serialization in java
Janu Jahnavi
 
PDF
Java Serialization
imypraz
 
PPT
Basics of java programming language
masud33bd
 
PPT
testing ppt
techweb08
 
PPTX
Core java complete ppt(note)
arvind pandey
 
PPT
Lecture d-inheritance
Tej Kiran
 
PDF
Java Serialization Deep Dive
Martijn Dashorst
 
PPTX
Java history, versions, types of errors and exception, quiz
SAurabh PRajapati
 
PPT
CS6270 Virtual Machines - Java Virtual Machine Architecture and APIs
Kwangshin Oh
 
PPTX
chap 10 : Development (scjp/ocjp)
It Academy
 
Class loader basic
명철 강
 
Understanding Java Dynamic Proxies
Rafael Luque Leiva
 
Dynamic Proxy by Java
Kan-Han (John) Lu
 
55 new things in Java 7 - Devoxx France
David Delabassee
 
Java Tutorial 1
Tushar Desarda
 
Advance java kvr -satya
Satya Johnny
 
Serialization & De-serialization in Java
InnovationM
 
Basics of java
onewomanmore witl
 
Smalltalk on the JVM
ESUG
 
Serialization in java
Janu Jahnavi
 
Java Serialization
imypraz
 
Basics of java programming language
masud33bd
 
testing ppt
techweb08
 
Core java complete ppt(note)
arvind pandey
 
Lecture d-inheritance
Tej Kiran
 
Java Serialization Deep Dive
Martijn Dashorst
 
Java history, versions, types of errors and exception, quiz
SAurabh PRajapati
 
CS6270 Virtual Machines - Java Virtual Machine Architecture and APIs
Kwangshin Oh
 
chap 10 : Development (scjp/ocjp)
It Academy
 
Ad

Viewers also liked (16)

PPTX
Java programming course for beginners
Eduonix Learning Solutions
 
PDF
Introduction to Java Programming Language
jaimefrozr
 
PPT
Java basic
Sonam Sharma
 
PPTX
Introduction to java
Veerabadra Badra
 
PPTX
Modul Kelas Programming : Java swing (session 2)
FgroupIndonesia
 
PPTX
Modul Kelas Programming : Introduction to java
FgroupIndonesia
 
PDF
OOP: Classes and Objects
Atit Patumvan
 
PDF
Java Generics: a deep dive
Bryan Basham
 
PPTX
Singleton class in Java
Rahul Sharma
 
PPT
Object and Classes in Java
backdoor
 
PPTX
Classes, objects in JAVA
Abhilash Nair
 
PPTX
Inheritance in java
Tech_MX
 
PPT
Core java concepts
Ram132
 
PDF
Introduction to Java Programming
Ravi Kant Sahu
 
PPT
Core java slides
Abhilash Nair
 
PPT
Java tutorial PPT
Intelligo Technologies
 
Java programming course for beginners
Eduonix Learning Solutions
 
Introduction to Java Programming Language
jaimefrozr
 
Java basic
Sonam Sharma
 
Introduction to java
Veerabadra Badra
 
Modul Kelas Programming : Java swing (session 2)
FgroupIndonesia
 
Modul Kelas Programming : Introduction to java
FgroupIndonesia
 
OOP: Classes and Objects
Atit Patumvan
 
Java Generics: a deep dive
Bryan Basham
 
Singleton class in Java
Rahul Sharma
 
Object and Classes in Java
backdoor
 
Classes, objects in JAVA
Abhilash Nair
 
Inheritance in java
Tech_MX
 
Core java concepts
Ram132
 
Introduction to Java Programming
Ravi Kant Sahu
 
Core java slides
Abhilash Nair
 
Java tutorial PPT
Intelligo Technologies
 
Ad

Similar to Java class loading tips and tricks - Java Colombo Meetup, January, 2014 (20)

PPT
Class
myrajendra
 
PPT
Class
myrajendra
 
PPT
Class
myrajendra
 
PPTX
Diving into Java Class Loader
Md Imran Hasan Hira
 
PDF
1669617800196.pdf
venud11
 
PDF
Advanced java jee material by KV Rao sir
AVINASH KUMAR
 
KEY
5 the final_hard_part
Honnix Liang
 
PDF
Adv kvr -satya
Jyothsna Sree
 
PPTX
Java Reflection Concept and Working
Software Productivity Strategists, Inc
 
PDF
Class method object
Minal Maniar
 
ODT
Perils Of Url Class Loader
Kaniska Mandal
 
PPTX
Framework prototype
DevMix
 
PPTX
Framework prototype
DevMix
 
PPTX
Framework prototype
DevMix
 
PPTX
inheritance and interface in oops with java .pptx
janetvidyaanancys
 
PPT
web program-Inheritance,pack&except in Java.ppt
mcjaya2024
 
PPTX
inheritance.pptx
sonukumarjha12
 
PPTX
Object Oriented Programming - Java
Daniel Ilunga
 
PPT
Java
javeed_mhd
 
PPTX
Java basics
Shivanshu Purwar
 
Class
myrajendra
 
Class
myrajendra
 
Class
myrajendra
 
Diving into Java Class Loader
Md Imran Hasan Hira
 
1669617800196.pdf
venud11
 
Advanced java jee material by KV Rao sir
AVINASH KUMAR
 
5 the final_hard_part
Honnix Liang
 
Adv kvr -satya
Jyothsna Sree
 
Java Reflection Concept and Working
Software Productivity Strategists, Inc
 
Class method object
Minal Maniar
 
Perils Of Url Class Loader
Kaniska Mandal
 
Framework prototype
DevMix
 
Framework prototype
DevMix
 
Framework prototype
DevMix
 
inheritance and interface in oops with java .pptx
janetvidyaanancys
 
web program-Inheritance,pack&except in Java.ppt
mcjaya2024
 
inheritance.pptx
sonukumarjha12
 
Object Oriented Programming - Java
Daniel Ilunga
 
Java basics
Shivanshu Purwar
 

More from Sameera Jayasoma (6)

PDF
Carbon 5 : A Preview
Sameera Jayasoma
 
PDF
Carbon and OSGi Deep Dive
Sameera Jayasoma
 
PDF
Building Multi-tenant SaaS Applications using WSO2 Private PaaS
Sameera Jayasoma
 
PDF
Using the Carbon Architecture to Build a Fit-for-Purpose Platform
Sameera Jayasoma
 
PDF
WSO2 Carbon Kernel Design and Architecture
Sameera Jayasoma
 
PDF
Demistifying OSGi - Colombo Java Meetup 2013
Sameera Jayasoma
 
Carbon 5 : A Preview
Sameera Jayasoma
 
Carbon and OSGi Deep Dive
Sameera Jayasoma
 
Building Multi-tenant SaaS Applications using WSO2 Private PaaS
Sameera Jayasoma
 
Using the Carbon Architecture to Build a Fit-for-Purpose Platform
Sameera Jayasoma
 
WSO2 Carbon Kernel Design and Architecture
Sameera Jayasoma
 
Demistifying OSGi - Colombo Java Meetup 2013
Sameera Jayasoma
 

Recently uploaded (20)

PDF
Advances in Ultra High Voltage (UHV) Transmission and Distribution Systems.pdf
Nabajyoti Banik
 
PDF
CIFDAQ'S Market Insight: BTC to ETH money in motion
CIFDAQ
 
PPTX
Coupa-Overview _Assumptions presentation
annapureddyn
 
PPTX
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
PDF
Using Anchore and DefectDojo to Stand Up Your DevSecOps Function
Anchore
 
PPTX
How to Build a Scalable Micro-Investing Platform in 2025 - A Founder’s Guide ...
Third Rock Techkno
 
PDF
Unlocking the Future- AI Agents Meet Oracle Database 23ai - AIOUG Yatra 2025.pdf
Sandesh Rao
 
PDF
Doc9.....................................
SofiaCollazos
 
PDF
NewMind AI Weekly Chronicles - July'25 - Week IV
NewMind AI
 
PDF
Building High-Performance Oracle Teams: Strategic Staffing for Database Manag...
SMACT Works
 
PDF
Chapter 1 Introduction to CV and IP Lecture Note.pdf
Getnet Tigabie Askale -(GM)
 
PDF
Automating ArcGIS Content Discovery with FME: A Real World Use Case
Safe Software
 
PDF
Software Development Methodologies in 2025
KodekX
 
PDF
Google I/O Extended 2025 Baku - all ppts
HusseinMalikMammadli
 
PPTX
Smart Infrastructure and Automation through IoT Sensors
Rejig Digital
 
PDF
Event Presentation Google Cloud Next Extended 2025
minhtrietgect
 
PDF
DevOps & Developer Experience Summer BBQ
AUGNYC
 
PDF
Accelerating Oracle Database 23ai Troubleshooting with Oracle AHF Fleet Insig...
Sandesh Rao
 
PDF
AI Unleashed - Shaping the Future -Starting Today - AIOUG Yatra 2025 - For Co...
Sandesh Rao
 
PDF
How Open Source Changed My Career by abdelrahman ismail
a0m0rajab1
 
Advances in Ultra High Voltage (UHV) Transmission and Distribution Systems.pdf
Nabajyoti Banik
 
CIFDAQ'S Market Insight: BTC to ETH money in motion
CIFDAQ
 
Coupa-Overview _Assumptions presentation
annapureddyn
 
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
Using Anchore and DefectDojo to Stand Up Your DevSecOps Function
Anchore
 
How to Build a Scalable Micro-Investing Platform in 2025 - A Founder’s Guide ...
Third Rock Techkno
 
Unlocking the Future- AI Agents Meet Oracle Database 23ai - AIOUG Yatra 2025.pdf
Sandesh Rao
 
Doc9.....................................
SofiaCollazos
 
NewMind AI Weekly Chronicles - July'25 - Week IV
NewMind AI
 
Building High-Performance Oracle Teams: Strategic Staffing for Database Manag...
SMACT Works
 
Chapter 1 Introduction to CV and IP Lecture Note.pdf
Getnet Tigabie Askale -(GM)
 
Automating ArcGIS Content Discovery with FME: A Real World Use Case
Safe Software
 
Software Development Methodologies in 2025
KodekX
 
Google I/O Extended 2025 Baku - all ppts
HusseinMalikMammadli
 
Smart Infrastructure and Automation through IoT Sensors
Rejig Digital
 
Event Presentation Google Cloud Next Extended 2025
minhtrietgect
 
DevOps & Developer Experience Summer BBQ
AUGNYC
 
Accelerating Oracle Database 23ai Troubleshooting with Oracle AHF Fleet Insig...
Sandesh Rao
 
AI Unleashed - Shaping the Future -Starting Today - AIOUG Yatra 2025 - For Co...
Sandesh Rao
 
How Open Source Changed My Career by abdelrahman ismail
a0m0rajab1
 

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

  • 1. Java Colombo Meetup January 16th, 2014 Java Class Loading: Tips and Tricks Sameera Jayasoma Software Architect WSO2
  • 4. Car myCar = new Car(); myCar is an object of the class Car. Bytecodes of the class Car is stored at Car.class file.
  • 5. Class myCarClass = myCar.getClass() Now what is myCarClass?
  • 6. 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.
  • 7. 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
  • 8. 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)
  • 9. 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.
  • 11. (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
  • 12. Agenda Basics of Java class loading <-Custom ClassLoaders Common class loading problems: Diagnosing and resolving them. J2EE class loading architectures Classloading in OSGi
  • 13. 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.
  • 14. 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.
  • 15. 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();
  • 16. Phases of Class Loading Three phase of class loading: Physical loading, linking and initializing.
  • 17. 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/
  • 18. Java ClassLoaders.. ● Initiating ClassLoader ○ ClassLoader that received the initial request to the load the class ● Defining ClassLoader ○ ClassLoader that actually loads the class.
  • 19. 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.
  • 21. 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/
  • 22. 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.
  • 23. Features of ClassLoaders.. 2) Delegation mode: ● Default is the parentfirst mode. http://patentimages.storage.googleapis.com/US7603666B2/US07603666-20091013D00002.png
  • 24. 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.
  • 25. Agenda Basics of Java class loading. Custom ClassLoaders <-Common class loading problems: Diagnosing and resolving them. J2EE class loading architectures Classloading in OSGi
  • 26. 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.
  • 27. 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; }
  • 28. 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.
  • 30. 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; }
  • 31. 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.
  • 32. Agenda Basics of Java class loading Custom ClassLoaders Common class loading problems: Diagnosing and resolving them. <-J2EE class loading architectures Classloading in OSGi
  • 33. 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.
  • 34. 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.
  • 35. 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
  • 36. 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.
  • 38. Agenda Basics of Java class loading Custom ClassLoaders Common class loading problems: Diagnosing and resolving them. J2EE class loading architectures <-Classloading in OSGi
  • 41. Agenda Basics of Java class loading Custom ClassLoaders Common class loading problems: Diagnosing and resolving them. J2EE class loading architectures Classloading in OSGi <--
  • 43. Class loading in OSGi Classloader Network. Delegate each other for classloading requests.