Skip to content

Commit 6d1302c

Browse files
committed
Fall back to default thread factory in case of error
When initializing virtual thread factory on Java 21+. Java 21 or more can be detected, but the thread factory initialization with reflection can fail on environments like GraalVM.
1 parent b43e2f8 commit 6d1302c

File tree

1 file changed

+18
-11
lines changed

1 file changed

+18
-11
lines changed

src/main/java/com/rabbitmq/stream/impl/ConcurrencyUtils.java

Lines changed: 18 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -28,24 +28,31 @@ final class ConcurrencyUtils {
2828
private static final ThreadFactory THREAD_FACTORY;
2929

3030
static {
31+
ThreadFactory tf;
3132
if (isJava21OrMore()) {
3233
LOGGER.debug("Running Java 21 or more, using virtual threads");
33-
Class<?> builderClass =
34-
Arrays.stream(Thread.class.getDeclaredClasses())
35-
.filter(c -> "Builder".equals(c.getSimpleName()))
36-
.findFirst()
37-
.get();
38-
// Reflection code is the same as:
39-
// Thread.ofVirtual().factory();
4034
try {
35+
Class<?> builderClass =
36+
Arrays.stream(Thread.class.getDeclaredClasses())
37+
.filter(c -> "Builder".equals(c.getSimpleName()))
38+
.findFirst()
39+
.get();
40+
// Reflection code is the same as:
41+
// Thread.ofVirtual().factory();
4142
Object builder = Thread.class.getDeclaredMethod("ofVirtual").invoke(null);
42-
THREAD_FACTORY = (ThreadFactory) builderClass.getDeclaredMethod("factory").invoke(builder);
43-
} catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
44-
throw new RuntimeException(e);
43+
tf = (ThreadFactory) builderClass.getDeclaredMethod("factory").invoke(builder);
44+
} catch (IllegalAccessException
45+
| InvocationTargetException
46+
| NoSuchMethodException
47+
| RuntimeException e) {
48+
LOGGER.debug("Error when creating virtual thread factory on Java 21+: {}", e.getMessage());
49+
LOGGER.debug("Falling back to default thread factory");
50+
tf = Executors.defaultThreadFactory();
4551
}
4652
} else {
47-
THREAD_FACTORY = Executors.defaultThreadFactory();
53+
tf = Executors.defaultThreadFactory();
4854
}
55+
THREAD_FACTORY = tf;
4956
}
5057

5158
private ConcurrencyUtils() {}

0 commit comments

Comments
 (0)