Skip to content

Commit

Permalink
Use thread factory for virtual threads
Browse files Browse the repository at this point in the history
This change makes ThreadPool use the supplied ThreadFactory also for virtual threads, which means they will have correct names etc
  • Loading branch information
cfredri4 authored and belaban committed Nov 19, 2024
1 parent f190fdd commit 167e931
Showing 1 changed file with 7 additions and 8 deletions.
15 changes: 7 additions & 8 deletions src/org/jgroups/util/ThreadPool.java
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
* @since 5.2
*/
public class ThreadPool implements Lifecycle {
private static final MethodHandle EXECUTORS_NEW_VIRTUAL_THREAD_FACTORY=getNewVirtualThreadFactoryHandle();
private static final MethodHandle EXECUTORS_NEW_THREAD_PER_TASK_EXECUTOR=getNewThreadPerTaskExecutorHandle();
protected Executor thread_pool;
protected Log log;
protected ThreadFactory thread_factory;
Expand Down Expand Up @@ -261,7 +261,7 @@ protected static ExecutorService createThreadPool(int min_threads, int max_threa
String rejection_policy,
BlockingQueue<Runnable> queue, final ThreadFactory factory,
Log log) {
if(!factory.useVirtualThreads() || EXECUTORS_NEW_VIRTUAL_THREAD_FACTORY == null) {
if(!factory.useVirtualThreads() || EXECUTORS_NEW_THREAD_PER_TASK_EXECUTOR == null) {
ThreadPoolExecutor pool=new ThreadPoolExecutor(min_threads, max_threads, keep_alive_time,
TimeUnit.MILLISECONDS, queue, factory);
RejectedExecutionHandler handler=Util.parseRejectionPolicy(rejection_policy);
Expand All @@ -272,19 +272,18 @@ protected static ExecutorService createThreadPool(int min_threads, int max_threa
}

try {
return (ExecutorService)EXECUTORS_NEW_VIRTUAL_THREAD_FACTORY.invokeExact();
return (ExecutorService)EXECUTORS_NEW_THREAD_PER_TASK_EXECUTOR.invokeExact((java.util.concurrent.ThreadFactory)factory);
}
catch(Throwable t) {
throw new IllegalStateException(String.format("failed to create virtual thread pool: %s", t));
}
}

protected static MethodHandle getNewVirtualThreadFactoryHandle() {
MethodType type=MethodType.methodType(ExecutorService.class);
protected static MethodHandle getNewThreadPerTaskExecutorHandle() {
MethodType type=MethodType.methodType(ExecutorService.class, java.util.concurrent.ThreadFactory.class);
String[] names={
"newVirtualThreadPerTaskExecutor", // jdk 18-21
"newVirtualThreadExecutor", // jdk 17
"newUnboundedVirtualThreadExecutor" // jdk 15 & 16
"newThreadPerTaskExecutor", // jdk 17+
"newUnboundedExecutor" // jdk 15 & 16
};

MethodHandles.Lookup LOOKUP=MethodHandles.publicLookup();
Expand Down

0 comments on commit 167e931

Please sign in to comment.