Classloader Namespace Isolation Example

0

In this article, I will show you an example of name space isolation.

If two name spaces correspond to class loaders that belong to different branches of the class-loading tree, those name spaces are isolated from each other and cannot see each other. For example, if classes A and B are loaded into two isolated name spaces,  A and B are totally unaware of each other’s presence.

Namespace Isolation Example

 

 

classloader_example_namespace_isolation

 

 

In this example, we have two branches of classloaders. In the first branch, class A is loaded by the classloader X. Since it is located in the classpath so it is loaded by the application classloader. In the second branch, I create a custom classloader Y with its parent as bootstrap classloader. Note if you pass NULL as the parent to URLClassLoader in it sconstructor, parent automatically becomes bootstrap classloader.

In the example, we have two code bases, classloaderX and classloaderY. I have bundled classloaderY classes into classloaderY.jar.
C:\javarticles_ws\classloaderY\bin>jar cf classloaderY.jar external

Class A is in classloaderX and class B is in classloaderY. Classloader X shouldn’t be able to load class B, likewise classloader Y shouldn’t be able to load A.

	public void testLoadClass() throws Exception {
        File jarFile = new File("C:/javarticles_ws/classloaderY/bin/classloaderY.jar");
        if (!jarFile.exists() || !jarFile.canRead()) {
            fail("not a valid jar");
        }
        URL[] urls = new URL[]{jarFile.toURI().toURL()};
        URLClassLoader customLoader = new URLClassLoader(urls, null);
        //Custom Classloader Y loads its own class B
        try {
            Class a = customLoader.loadClass("external.B"); 
            assertNotNull(a);            
        } catch (ClassNotFoundException e) {
            fail(e.toString());
        }
        //Y classloader can't see class A from classloader X
        try {
            Class b = customLoader.loadClass("javarticles.A");
            fail("Should not be able to access " + b.getCanonicalName());
        } catch (ClassNotFoundException e) {
        }
        //X classloader can't see class B from classloader Y
        try {
            Class a = getClass().getClassLoader().loadClass("external.B");
            fail("Should not be able to access " + a.getCanonicalName());
        } catch (ClassNotFoundException e) {
        }
    }

Download the project classloader

Share.

Leave A Reply