SlideShare uma empresa Scribd logo
1 de 45
Baixar para ler offline
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 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.
(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.
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.
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!!!

Mais conteúdo relacionado

Mais procurados

Class loader basic
Class loader basicClass loader basic
Class loader basic명철 강
 
Understanding Java Dynamic Proxies
Understanding Java Dynamic ProxiesUnderstanding Java Dynamic Proxies
Understanding Java Dynamic ProxiesRafael Luque Leiva
 
55 new things in Java 7 - Devoxx France
55 new things in Java 7 - Devoxx France55 new things in Java 7 - Devoxx France
55 new things in Java 7 - Devoxx FranceDavid Delabassee
 
Advance java kvr -satya
Advance java  kvr -satyaAdvance java  kvr -satya
Advance java kvr -satyaSatya Johnny
 
Serialization & De-serialization in Java
Serialization & De-serialization in JavaSerialization & De-serialization in Java
Serialization & De-serialization in JavaInnovationM
 
Smalltalk on the JVM
Smalltalk on the JVMSmalltalk on the JVM
Smalltalk on the JVMESUG
 
Serialization in java
Serialization in javaSerialization in java
Serialization in javaJanu Jahnavi
 
Java Serialization
Java SerializationJava Serialization
Java Serializationimypraz
 
Basics of java programming language
Basics of java programming languageBasics of java programming language
Basics of java programming languagemasud33bd
 
Core java complete ppt(note)
Core java  complete  ppt(note)Core java  complete  ppt(note)
Core java complete ppt(note)arvind pandey
 
Lecture d-inheritance
Lecture d-inheritanceLecture d-inheritance
Lecture d-inheritanceTej Kiran
 
Java Serialization Deep Dive
Java Serialization Deep DiveJava Serialization Deep Dive
Java Serialization Deep DiveMartijn Dashorst
 
Java history, versions, types of errors and exception, quiz
Java history, versions, types of errors and exception, quiz Java history, versions, types of errors and exception, quiz
Java history, versions, types of errors and exception, quiz SAurabh PRajapati
 
CS6270 Virtual Machines - Java Virtual Machine Architecture and APIs
CS6270 Virtual Machines - Java Virtual Machine Architecture and APIsCS6270 Virtual Machines - Java Virtual Machine Architecture and APIs
CS6270 Virtual Machines - Java Virtual Machine Architecture and APIsKwangshin Oh
 
chap 10 : Development (scjp/ocjp)
chap 10 : Development (scjp/ocjp)chap 10 : Development (scjp/ocjp)
chap 10 : Development (scjp/ocjp)It Academy
 

Mais procurados (20)

Class loader basic
Class loader basicClass loader basic
Class loader basic
 
Understanding Java Dynamic Proxies
Understanding Java Dynamic ProxiesUnderstanding Java Dynamic Proxies
Understanding Java Dynamic Proxies
 
Dynamic Proxy by Java
Dynamic Proxy by JavaDynamic Proxy by Java
Dynamic Proxy by Java
 
Class loaders
Class loadersClass loaders
Class loaders
 
55 new things in Java 7 - Devoxx France
55 new things in Java 7 - Devoxx France55 new things in Java 7 - Devoxx France
55 new things in Java 7 - Devoxx France
 
Java Tutorial 1
Java Tutorial 1Java Tutorial 1
Java Tutorial 1
 
Advance java kvr -satya
Advance java  kvr -satyaAdvance java  kvr -satya
Advance java kvr -satya
 
Serialization & De-serialization in Java
Serialization & De-serialization in JavaSerialization & De-serialization in Java
Serialization & De-serialization in Java
 
Basics of java
Basics of javaBasics of java
Basics of java
 
Smalltalk on the JVM
Smalltalk on the JVMSmalltalk on the JVM
Smalltalk on the JVM
 
Serialization in java
Serialization in javaSerialization in java
Serialization in java
 
Java Serialization
Java SerializationJava Serialization
Java Serialization
 
Basics of java programming language
Basics of java programming languageBasics of java programming language
Basics of java programming language
 
testing ppt
testing ppttesting ppt
testing ppt
 
Core java complete ppt(note)
Core java  complete  ppt(note)Core java  complete  ppt(note)
Core java complete ppt(note)
 
Lecture d-inheritance
Lecture d-inheritanceLecture d-inheritance
Lecture d-inheritance
 
Java Serialization Deep Dive
Java Serialization Deep DiveJava Serialization Deep Dive
Java Serialization Deep Dive
 
Java history, versions, types of errors and exception, quiz
Java history, versions, types of errors and exception, quiz Java history, versions, types of errors and exception, quiz
Java history, versions, types of errors and exception, quiz
 
CS6270 Virtual Machines - Java Virtual Machine Architecture and APIs
CS6270 Virtual Machines - Java Virtual Machine Architecture and APIsCS6270 Virtual Machines - Java Virtual Machine Architecture and APIs
CS6270 Virtual Machines - Java Virtual Machine Architecture and APIs
 
chap 10 : Development (scjp/ocjp)
chap 10 : Development (scjp/ocjp)chap 10 : Development (scjp/ocjp)
chap 10 : Development (scjp/ocjp)
 

Destaque

Introduction to Java Programming Language
Introduction to Java Programming LanguageIntroduction to Java Programming Language
Introduction to Java Programming Languagejaimefrozr
 
Modul Kelas Programming : Java swing (session 2)
Modul Kelas Programming : Java swing (session 2)Modul Kelas Programming : Java swing (session 2)
Modul Kelas Programming : Java swing (session 2)FgroupIndonesia
 
Modul Kelas Programming : Introduction to java
Modul Kelas Programming : Introduction to javaModul Kelas Programming : Introduction to java
Modul Kelas Programming : Introduction to javaFgroupIndonesia
 
OOP: Classes and Objects
OOP: Classes and ObjectsOOP: Classes and Objects
OOP: Classes and ObjectsAtit Patumvan
 
Java Generics: a deep dive
Java Generics: a deep diveJava Generics: a deep dive
Java Generics: a deep diveBryan Basham
 
Singleton class in Java
Singleton class in JavaSingleton class in Java
Singleton class in JavaRahul Sharma
 
Object and Classes in Java
Object and Classes in JavaObject and Classes in Java
Object and Classes in Javabackdoor
 
Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVAAbhilash Nair
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in javaTech_MX
 
Core java concepts
Core java  conceptsCore java  concepts
Core java conceptsRam132
 
Introduction to Java Programming
Introduction to Java ProgrammingIntroduction to Java Programming
Introduction to Java ProgrammingRavi Kant Sahu
 

Destaque (16)

Java programming course for beginners
Java programming course for beginnersJava programming course for beginners
Java programming course for beginners
 
Introduction to Java Programming Language
Introduction to Java Programming LanguageIntroduction to Java Programming Language
Introduction to Java Programming Language
 
Java basic
Java basicJava basic
Java basic
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to java
 
Modul Kelas Programming : Java swing (session 2)
Modul Kelas Programming : Java swing (session 2)Modul Kelas Programming : Java swing (session 2)
Modul Kelas Programming : Java swing (session 2)
 
Modul Kelas Programming : Introduction to java
Modul Kelas Programming : Introduction to javaModul Kelas Programming : Introduction to java
Modul Kelas Programming : Introduction to java
 
OOP: Classes and Objects
OOP: Classes and ObjectsOOP: Classes and Objects
OOP: Classes and Objects
 
Java Generics: a deep dive
Java Generics: a deep diveJava Generics: a deep dive
Java Generics: a deep dive
 
Singleton class in Java
Singleton class in JavaSingleton class in Java
Singleton class in Java
 
Object and Classes in Java
Object and Classes in JavaObject and Classes in Java
Object and Classes in Java
 
Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVA
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
 
Core java concepts
Core java  conceptsCore java  concepts
Core java concepts
 
Introduction to Java Programming
Introduction to Java ProgrammingIntroduction to Java Programming
Introduction to Java Programming
 
Core java slides
Core java slidesCore java slides
Core java slides
 
Java tutorial PPT
Java tutorial PPTJava tutorial PPT
Java tutorial PPT
 

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

Semelhante a Java class loading tips and tricks - Java Colombo Meetup, January, 2014 (20)

Class
ClassClass
Class
 
Class
ClassClass
Class
 
Class
ClassClass
Class
 
Diving into Java Class Loader
Diving into Java Class LoaderDiving into Java Class Loader
Diving into Java Class Loader
 
1669617800196.pdf
1669617800196.pdf1669617800196.pdf
1669617800196.pdf
 
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sirAdvanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sir
 
5 the final_hard_part
5 the final_hard_part5 the final_hard_part
5 the final_hard_part
 
Adv kvr -satya
Adv  kvr -satyaAdv  kvr -satya
Adv kvr -satya
 
Java Reflection Concept and Working
Java Reflection Concept and WorkingJava Reflection Concept and Working
Java Reflection Concept and Working
 
Class method object
Class method objectClass method object
Class method object
 
Perils Of Url Class Loader
Perils Of Url Class LoaderPerils Of Url Class Loader
Perils Of Url Class Loader
 
Framework prototype
Framework prototypeFramework prototype
Framework prototype
 
Framework prototype
Framework prototypeFramework prototype
Framework prototype
 
Framework prototype
Framework prototypeFramework prototype
Framework prototype
 
inheritance.pptx
inheritance.pptxinheritance.pptx
inheritance.pptx
 
Object Oriented Programming - Java
Object Oriented Programming -  JavaObject Oriented Programming -  Java
Object Oriented Programming - Java
 
Java
JavaJava
Java
 
Java basics
Java basicsJava basics
Java basics
 
Sonu wiziq
Sonu wiziqSonu wiziq
Sonu wiziq
 
javapackage
javapackagejavapackage
javapackage
 

Mais de Sameera Jayasoma

Building Multi-tenant SaaS Applications using WSO2 Private PaaS
Building Multi-tenant SaaS Applications using WSO2 Private PaaSBuilding Multi-tenant SaaS Applications using WSO2 Private PaaS
Building Multi-tenant SaaS Applications using WSO2 Private PaaSSameera Jayasoma
 
Using the Carbon Architecture to Build a Fit-for-Purpose Platform
Using the Carbon Architecture to Build a Fit-for-Purpose PlatformUsing the Carbon Architecture to Build a Fit-for-Purpose Platform
Using the Carbon Architecture to Build a Fit-for-Purpose PlatformSameera Jayasoma
 
WSO2 Carbon Kernel Design and Architecture
WSO2 Carbon Kernel Design and ArchitectureWSO2 Carbon Kernel Design and Architecture
WSO2 Carbon Kernel Design and ArchitectureSameera Jayasoma
 
Demistifying OSGi - Colombo Java Meetup 2013
Demistifying OSGi - Colombo Java Meetup 2013Demistifying OSGi - Colombo Java Meetup 2013
Demistifying OSGi - Colombo Java Meetup 2013Sameera Jayasoma
 

Mais de Sameera Jayasoma (6)

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

Último

2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 

Último (20)

2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 

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
  • 2.
  • 3. 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.
  • 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.
  • 10.
  • 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.
  • 20.
  • 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.
  • 29.
  • 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.