CompletableFuture / ForkJoinPool Set Class Loader
I ran into something similar and came up with a solution that does not use reflection and seems to work well with JDK9-JDK11.
Here is what the javadocs say:
The parameters used to construct the common pool may be controlled by setting the following system properties:
- java.util.concurrent.ForkJoinPool.common.threadFactory - the class name of a ForkJoinPool.ForkJoinWorkerThreadFactory. The system class loader is used to load this class.
So if you rollout your own version of the ForkJoinWorkerThreadFactory
and set that instead to use the correct ClassLoader
using the system property, this should work.
Here is my custom ForkJoinWorkerThreadFactory
:
package foo;
public class MyForkJoinWorkerThreadFactory implements ForkJoinWorkerThreadFactory {
@Override
public final ForkJoinWorkerThread newThread(ForkJoinPool pool) {
return new MyForkJoinWorkerThread(pool);
}
private static class MyForkJoinWorkerThread extends ForkJoinWorkerThread {
private MyForkJoinWorkerThread(final ForkJoinPool pool) {
super(pool);
// set the correct classloader here
setContextClassLoader(Thread.currentThread().getContextClassLoader());
}
}
}
and then set the system property in your app startup script
-Djava.util.concurrent.ForkJoinPool.common.threadFactory=foo.MyForkJoinWorkerThreadFactory
The above solution works assuming that when the ForkJoinPool class is referenced the first time and it initializes the commonPool
, the context ClassLoader for this Thread is the correct one that you need (and is not the System class loader).
Here is some background that might help:
Fork/Join common pool threads return the system class loader as their thread context class loader.
In Java SE 9, threads that are part of the fork/join common pool will always return the system class loader as their thread context class loader. In previous releases, the thread context class loader may have been inherited from whatever thread causes the creation of the fork/join common pool thread, e.g. by submitting a task. An application cannot reliably depend on when, or how, threads are created by the fork/join common pool, and as such cannot reliably depend on a custom defined class loader to be set as the thread context class loader.
As a result of the above backward incompatibility change, things that uses the ForkJoinPool
that used to worked in JDK8 may not work in JDK9+ .
One possible solution valid in jdk11 (tested using Spring Boot 2.2) is to take advantage of the new constructors in ForkJoinPool
The main idea is to create a custom ForkJoinPool
using a custom ThreadFactory that uses our own ClassLoader (not the system one -this behavior starts in jdk9-)
A bit of history
Before jdk9 ForkJoinPool.common()
returns an Executor with a ClassLoader of your main Thread, in Java 9 this behave changes, and return an executor with the system jdk system classloader.
So it's easy to find ClassNotFoundExceptions inside CompletableFutures code while upgrading from Java 8 to Java 9 / 10 / 11, due to this change.
Solution Create our own factory like Neo said in an anwser before and use this factory yo create a ForkJoinPool and an Executor
MyForkJoinWorkerThreadFactory factory = new MyForkJoinWorkerThreadFactory();
ForkJoinPool myCommonPool = new ForkJoinPool(Math.min(32767, Runtime.getRuntime().availableProcessors()), factory, null, false);
Use it like this
CompletableFuture.runAsync(() -> {
log.info(Thread.currentThread().getName()+" "+Thread.currentThread().getContextClassLoader().toString());
// will print the classloader from the Main Thread, not the jdk system one :)
}, myCommonPool).join();
Extraball
If your are behind a Spring based app, should be necesary to add your Spring Security Context to the new custom thread pool
@Bean(name = "customExecutor")
public Executor customExecutor() {
MyForkJoinWorkerThreadFactory factory = new MyForkJoinWorkerThreadFactory();
ForkJoinPool myCommonPool = new ForkJoinPool(Math.min(32767, Runtime.getRuntime().availableProcessors()), factory, null, false);
DelegatingSecurityContextExecutor delegatingExecutorCustom = new DelegatingSecurityContextExecutor(myCommonPool, SecurityContextHolder.getContext());
return delegatingExecutorCustom;
}
And use it autowiring like any other resource
@Autowired private Executor customExecutor;
CompletableFuture.runAsync(() -> {
....
}, customExecutor).join();
So, here is a very dirty solution of which I'm not proud of and may break things for you if you go along with it:
The problem was that the classloader of the application was not used for ForkJoinPool.commonPool()
. Because the setup of commonPool is static and therefor during the application start up there is no easy possibility (at least to my knowledge) to make changes later. So we need to rely on Java reflection API.
create a hook after your application successfully started
- in my case (Spring Boot environment) this will be the ApplicationReadyEvent
to listen to this event you need a component like the following
@Component class ForkJoinCommonPoolFix : ApplicationListener<ApplicationReadyEvent> { override fun onApplicationEvent(event: ApplicationReadyEvent?) { } }
Inside your hook you need to set
ForkJoinWorkerThreadFactory
of commonPool to a custom implementation (so this custom implementation will use the app classloader)in Kotlin
val javaClass = ForkJoinPool.commonPool()::class.java val field = javaClass.getDeclaredField("factory") field.isAccessible = true val modifiers = field::class.java.getDeclaredField("modifiers") modifiers.isAccessible = true modifiers.setInt(field, field.modifiers and Modifier.FINAL.inv()) field.set(ForkJoinPool.commonPool(), CustomForkJoinWorkerThreadFactory()) field.isAccessible = false
Simple implementation of
CustomForkJoinWorkerThreadFactory
in Kotlin
//Custom class class CustomForkJoinWorkerThreadFactory : ForkJoinPool.ForkJoinWorkerThreadFactory { override fun newThread(pool: ForkJoinPool?): ForkJoinWorkerThread { return CustomForkJoinWorkerThread(pool) } } // helper class (probably only needed in kotlin) class CustomForkJoinWorkerThread(pool: ForkJoinPool?) : ForkJoinWorkerThread(pool)
If you need more information about reflection and why it's not good to change final fields please refer to here and here. Short summary: due to optimizations the updated final field may not be visible to other objects and other unknown side effects may occur.
As stated before: this is a very dirty solution. Unwanted side effects may occur if you use this solution. Using reflections like this is not a good idea. If you can use a solution without reflection (and post it as an answer here!).
Edit: Alternative for single calls
Like stated in the question itself: if you only have this problem in a small number of places (i.e. it's no problem to fix the call itself) you can use your own Executor. A simple example copied from here:
ExecutorService pool = Executors.newFixedThreadPool(10);
final CompletableFuture<String> future =
CompletableFuture.supplyAsync(() -> { /* ... */ }, pool);