java class loading tips and tricks - java colombo meetup, january, 2014

45
Java Class Loading: Tips and Tricks Sameera Jayasoma Software Architect WSO2 Java Colombo Meetup January 16th, 2014

Upload: sameera-jayasoma

Post on 17-Dec-2014

2.840 views

Category:

Technology


2 download

DESCRIPTION

 

TRANSCRIPT

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

Java Class Loading: Tips and Tricks

Sameera JayasomaSoftware Architect

WSO2

Java Colombo MeetupJanuary 16th, 2014

Page 2: Java class loading  tips and tricks - Java Colombo Meetup, January, 2014
Page 3: Java class loading  tips and tricks - Java Colombo Meetup, January, 2014

Java Objects

Java objects consist of state and behaviour just like any real-world object.

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

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

Car myCar = new Car();

myCar is an object of the class Car.Bytecodes of the class Car is stored at Car.class file.

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

Class myCarClass = myCar.getClass()

Now what is myCarClass?

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

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.

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

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

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

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)

http://en.wikipedia.org/wiki/Java_virtual_machine

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

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.

Page 10: Java class loading  tips and tricks - Java Colombo Meetup, January, 2014
Page 11: 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

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

Agenda

Basics of Java class loading <--Custom ClassLoadersCommon class loading problems: Diagnosing and resolving them.J2EE class loading architecturesClassloading in OSGi

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

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.

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

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.

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

● 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();

Java Class Loading..

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

Phases of Class Loading

Three phase of class loading: Physical loading, linking and initializing.

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

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/

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

Java ClassLoaders..● Initiating ClassLoader

○ ClassLoader that received the initial request to the load the class

● Defining ClassLoader○ ClassLoader that actually loads the class.

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

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.

Page 20: Java class loading  tips and tricks - Java Colombo Meetup, January, 2014
Page 21: 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/

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

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.

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

Features of ClassLoaders..

http://patentimages.storage.googleapis.com/US7603666B2/US07603666-20091013-D00002.png

2) Delegation mode: ● Default is the parent-

first mode.

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

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.

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

Agenda

Basics of Java class loading.Custom ClassLoaders <--Common class loading problems: Diagnosing and resolving them.J2EE class loading architecturesClassloading in OSGi

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

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.

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

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;}

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

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.

Page 29: Java class loading  tips and tricks - Java Colombo Meetup, January, 2014
Page 30: Java class loading  tips and tricks - Java Colombo Meetup, January, 2014

Creating a Custom ClassLoaderpublic 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;

}

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

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.

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

Agenda

Basics of Java class loadingCustom ClassLoadersCommon class loading problems: Diagnosing and resolving them. <--J2EE class loading architecturesClassloading in OSGi

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

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.

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

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.

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

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

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

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.

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

LinkageErrors

Subclasses:● AbstractMethodError● ClassCircularityError● ClassFormatError● NoSuchMethodError● ..

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

Agenda

Basics of Java class loadingCustom ClassLoadersCommon class loading problems: Diagnosing and resolving them.J2EE class loading architectures <--Classloading in OSGi

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

Tomcat

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

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

JBOSS 4.0.x

http://www.infoq.com/presentations/java-classloading-architectures-ernie-svehla

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

Agenda

Basics of Java class loadingCustom ClassLoadersCommon class loading problems: Diagnosing and resolving them.J2EE class loading architecturesClassloading in OSGi <--

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

What is OSGi?

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

Class loading in OSGi

Classloader Network.

Delegate each other for

classloading requests.

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

References● http://www.infoq.com/presentations/java-classloading-architectures-

ernie-svehla

● http://www2.sys-con.com/itsg/virtualcd/java/archives/0808/chaudhri/index.html

● http://www.techjava.de/topics/2008/01/java-class-loading/

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

Thank You!!!

http://www.smileysymbol.com/2012/05/smiley-face-collection-10-pics.html