Skip to content

Commit c78698c

Browse files
committed
Populate RandomizedContext for virtual thread group
1 parent 88526bc commit c78698c

File tree

1 file changed

+26
-3
lines changed

1 file changed

+26
-3
lines changed

test/framework/src/main/java/org/elasticsearch/test/ESTestCase.java

Lines changed: 26 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -210,6 +210,7 @@
210210
import java.util.concurrent.TimeUnit;
211211
import java.util.concurrent.TimeoutException;
212212
import java.util.concurrent.atomic.AtomicInteger;
213+
import java.util.concurrent.atomic.AtomicReference;
213214
import java.util.function.BooleanSupplier;
214215
import java.util.function.Consumer;
215216
import java.util.function.IntConsumer;
@@ -435,20 +436,29 @@ private static void forceImmutableCollectionsSeed(long seed) {
435436
}
436437
}
437438

439+
private static final AtomicReference<RandomizedContext> virtualThreadsContext = new AtomicReference<>();
440+
438441
/**
439442
* This is an awful hack to work around the fact the virtual threads' thread group
440443
* doesn't have a {@link RandomizedContext}. There's probably a way to do this
441444
* that isn't a nasty hack, but that's a job for another day.
442445
*/
443-
@Before
444-
public void fudgeRandomContextForVirtualThreads() {
446+
@BeforeClass
447+
public static void fudgeRandomContextForVirtualThreads() {
445448
final RandomizedContext current = RandomizedContext.current();
446449
try {
447450
Method create = RandomizedContext.class.getDeclaredMethod("create", ThreadGroup.class, Class.class, RandomizedRunner.class);
448451
create.setAccessible(true);
449452
Thread.ofVirtual().start(() -> {
450453
try {
451-
create.invoke(null, Thread.currentThread().getThreadGroup(), current.getTargetClass(), current.getRunner());
454+
virtualThreadsContext.set(
455+
(RandomizedContext) create.invoke(
456+
null,
457+
Thread.currentThread().getThreadGroup(),
458+
current.getTargetClass(),
459+
current.getRunner()
460+
)
461+
);
452462
} catch (Exception e) {
453463
fail(e, "Hack didn't work");
454464
}
@@ -458,6 +468,19 @@ public void fudgeRandomContextForVirtualThreads() {
458468
}
459469
}
460470

471+
@AfterClass
472+
public static void cleanUpMess() {
473+
if (virtualThreadsContext.get() != null) {
474+
try {
475+
final Method dispose = RandomizedContext.class.getDeclaredMethod("dispose");
476+
dispose.setAccessible(true);
477+
dispose.invoke(virtualThreadsContext.get());
478+
} catch (Exception e) {
479+
fail(e, "Hack didn't work");
480+
}
481+
}
482+
}
483+
461484
@SuppressForbidden(reason = "force log4j and netty sysprops")
462485
private static void setTestSysProps(Random random) {
463486
System.setProperty("log4j.shutdownHookEnabled", "false");

0 commit comments

Comments
 (0)