java - 异步 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();
我知道我的代码有效,当它全部在一个线程上运行时它工作正常。
解决方案
解决方案是创建一个新的 URLClassLoader,因为 URLPathLoader 似乎不是线程安全的,并将 Thread 的上下文类加载器设置为 URLClassLoader。一种没有解释的解决方法,但这就是我能想到的。
推荐阅读
- html - Bootstrap 4 - 更改导航栏品牌字体
- python - Python-eve:使用 current_app.data.driver.db[collection].update_one() 直接更新时是否尊重架构?
- java - Java拆分函数将字符后的空格读取为空字符串
- javascript - 如何正确拆分 React 应用程序组件
- json - 将 JSON 转换为 Gpath 结果
- swift - 在 Swift 中同时搜索两个元素?
- php - PHP Laravel:如何限制对 laravel 中文件的直接访问(http://localhost/projectname/public/uploads/sample.pdf)
- python - 当我创建一个基于类的生成器时,为什么我必须调用下一个?
- java - 想要在 linux (utf-8 默认) 中转换在 windows (base64) 中生成的文件
- c++ - c++ 函数程序中的平均输出始终为 0.0