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

Preview:

DESCRIPTION

 

Citation preview

Java Class Loading: Tips and Tricks

Sameera JayasomaSoftware Architect

WSO2

Java Colombo MeetupJanuary 16th, 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

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

● 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

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 ClassLoadersCommon class loading problems: Diagnosing and resolving them.J2EE class loading architecturesClassloading 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.

● 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..

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..

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

2) Delegation mode: ● Default is the parent-

first mode.

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

}

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 loadingCustom ClassLoadersCommon class loading problems: Diagnosing and resolving them. <--J2EE class loading architecturesClassloading 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 loadingCustom ClassLoadersCommon 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 loadingCustom ClassLoadersCommon class loading problems: Diagnosing and resolving them.J2EE class loading architecturesClassloading 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-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/

Thank You!!!

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

Recommended