首页 > 解决方案 > 异步 URLClassLoader 抛出 ClassNotFoundException

问题描述

我正在尝试异步加载类文件,但似乎每次我尝试异步加载时,它都会抛出 ClassNotFoundException。

查看该类的源代码,ClassLoader 应该异步工作(它会自行同步),但只有当我从与创建 URLClassLoader 的位置不同的线程加载类时才会遇到问题。

示例:线程 1 加载 URL 并创建 URLClassLoader 线程 2 使用 URLClassLoader 加载 my/example/Foo.class。它将 my.example.Foo 传递给 ClassLoader#loadClass(String),并抛出 ClassNotFoundException。

示例代码:

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();

我知道我的代码有效,当它全部在一个线程上运行时它工作正常。

标签: javaasynchronous

解决方案


解决方案是创建一个新的 URLClassLoader,因为 URLPathLoader 似乎不是线程安全的,并将 Thread 的上下文类加载器设置为 URLClassLoader。一种没有解释的解决方法,但这就是我能想到的。


推荐阅读