简体   繁体   中英

UrlClassLoader scope

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM