简体   繁体   中英

Async URLClassLoader throws ClassNotFoundException

I'm trying to asynchronously load class files, but it seems every time I try to do it async, it throws a ClassNotFoundException.

Looking through the source for the class, ClassLoader should work async (It synchronizes itself), yet I only get the problem when I load a class from a different thread than where the URLClassLoader was created.

Example: Thread 1 loads the URLs and creates the URLClassLoader Thread 2 uses the URLClassLoader to load my/example/Foo.class. It passes my.example.Foo to ClassLoader#loadClass(String), and a ClassNotFoundException is thrown.

Example code:

URLClassLoader loader = new URLClassLoader(myJarURLs, getClass().getClassLoader());
ExecutorService executor = Executors.newCachedThreadPool();
CompleteableFuture.supplyAsync(() ->  {
    Thread.currentThread().setContextClassLoader(loader);
    loader.loadClass("my.example.Foo")
}, executor);
executor.shutdown();

I know my code works, it works fine when it all runs on one thread.

The solution was to create a new URLClassLoader because URLPathLoader appears to not be thread safe, and to set the Thread's context class loader to the URLClassLoader. Kind of a work around with no explanation, but that's all I could figure out.

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