UrlClassLoader scope

399 views Asked by At

I am using URLClassLoader to load classes from an external jar file,the classes loaded by this might be already present in my web application classloader, suppose URL classloader loaded class A with version 1 and webapplication already loaded same class A with version2, A new thread started by webapplication needs class A, could this get A from UrlClassloader instead of webapplication classloader? if so how can I avoid this , how can I limit the urlclassloader classes scope to serve only in a specific method?

Please advice setting the classloader in

Thread.currentThread().getContextClassLoader();

do my work which deals with classes from this classloader and once done replace it with old classloader?

ClassLoader oldLoader=Thread.currentThread().getContextClassLoader();
            Thread.currentThread().setContextClassLoader(classLoader);
            try{
                siClass=classLoader.loadClass("tools.ds.Signature3");
                result=doWork();
            }catch(Exception e){
                throw new RuntimeException(e);
            }finally{
                Thread.currentThread().setContextClassLoader(oldLoader);
            }
            return result;

This way am I restricting scope of classLoader only to doWork() operation?

1

There are 1 answers

0
user3707125 On

The answer is in the javadoc of Thread.getContextClassLoader():

Returns the context ClassLoader for this Thread. The context ClassLoader is provided by the creator of the thread for use by code running in this thread when loading classes and resources. If not set, the default is the ClassLoader context of the parent Thread. The context ClassLoader of the primordial thread is typically set to the class loader used to load the application.

So if you were not messing with that URLClassLoader it should not affect your threads.