From 26d91aedaef91ff0ec74f2b7249350317bd61029 Mon Sep 17 00:00:00 2001 From: Matthew de Detrich Date: Sun, 29 Nov 2026 22:12:10 +0100 Subject: [PATCH 1/4] Allow customizing the thread factories of Testcontainers' own threads Testcontainers runs some of its work on threads it creates itself: the wait strategy and Startables pools, the image pull watchdog, the Ryuk connection thread and the R2DBC pool. Most of these are static pools shared by the whole JVM that create their threads lazily, on whichever thread first needs one, and their thread factories are private. Tools that track state per thread can't keep that state from leaking into these shared threads. For example, a test framework that inherits the current test into threads created while it runs ends up attributing a shared pool thread, and its output, to whichever test happened to create it. Add a ThreadFactoryCustomizer SPI, loaded via ServiceLoader like CreateContainerCmdModifier. Each customizer receives the factory Testcontainers would otherwise use and returns the one to use instead. Customizers are loaded once, when the first pool is created, and one that throws or returns null is skipped with a warning. Co-Authored-By: Claude Opus 5.5 --- .../wait/strategy/AbstractWaitStrategy.java | 19 +++--- .../core/ThreadFactoryCustomizer.java | 26 ++++++++ ...eLimitedLoggedPullImageResultCallback.java | 5 +- .../testcontainers/lifecycle/Startables.java | 19 +++--- .../utility/RyukResourceReaper.java | 12 ++-- .../utility/ThreadFactoryCustomizers.java | 61 ++++++++++++++++++ .../AbstractWaitStrategyExecutorTest.java | 18 ++++++ .../custom/TestThreadFactoryCustomizer.java | 24 +++++++ .../utility/ThreadFactoryCustomizersTest.java | 64 +++++++++++++++++++ ...estcontainers.core.ThreadFactoryCustomizer | 1 + docs/features/advanced_options.md | 21 ++++++ .../TestcontainersR2DBCConnectionFactory.java | 15 +++-- 12 files changed, 255 insertions(+), 30 deletions(-) create mode 100644 core/src/main/java/org/testcontainers/core/ThreadFactoryCustomizer.java create mode 100644 core/src/main/java/org/testcontainers/utility/ThreadFactoryCustomizers.java create mode 100644 core/src/test/java/org/testcontainers/containers/wait/strategy/AbstractWaitStrategyExecutorTest.java create mode 100644 core/src/test/java/org/testcontainers/custom/TestThreadFactoryCustomizer.java create mode 100644 core/src/test/java/org/testcontainers/utility/ThreadFactoryCustomizersTest.java create mode 100644 core/src/test/resources/META-INF/services/org.testcontainers.core.ThreadFactoryCustomizer diff --git a/core/src/main/java/org/testcontainers/containers/wait/strategy/AbstractWaitStrategy.java b/core/src/main/java/org/testcontainers/containers/wait/strategy/AbstractWaitStrategy.java index 4adf28406b6..5521fcd2643 100644 --- a/core/src/main/java/org/testcontainers/containers/wait/strategy/AbstractWaitStrategy.java +++ b/core/src/main/java/org/testcontainers/containers/wait/strategy/AbstractWaitStrategy.java @@ -3,6 +3,7 @@ import lombok.NonNull; import org.rnorth.ducttape.ratelimits.RateLimiter; import org.rnorth.ducttape.ratelimits.RateLimiterBuilder; +import org.testcontainers.utility.ThreadFactoryCustomizers; import java.time.Duration; import java.util.Set; @@ -15,16 +16,18 @@ public abstract class AbstractWaitStrategy implements WaitStrategy { static final ExecutorService EXECUTOR = Executors.newCachedThreadPool( - new ThreadFactory() { - private final AtomicLong COUNTER = new AtomicLong(0); + ThreadFactoryCustomizers.customize( + new ThreadFactory() { + private final AtomicLong COUNTER = new AtomicLong(0); - @Override - public Thread newThread(Runnable r) { - Thread thread = new Thread(r, "testcontainers-wait-" + COUNTER.getAndIncrement()); - thread.setDaemon(true); - return thread; + @Override + public Thread newThread(Runnable r) { + Thread thread = new Thread(r, "testcontainers-wait-" + COUNTER.getAndIncrement()); + thread.setDaemon(true); + return thread; + } } - } + ) ); private static final RateLimiter DOCKER_CLIENT_RATE_LIMITER = RateLimiterBuilder diff --git a/core/src/main/java/org/testcontainers/core/ThreadFactoryCustomizer.java b/core/src/main/java/org/testcontainers/core/ThreadFactoryCustomizer.java new file mode 100644 index 00000000000..a95352bada9 --- /dev/null +++ b/core/src/main/java/org/testcontainers/core/ThreadFactoryCustomizer.java @@ -0,0 +1,26 @@ +package org.testcontainers.core; + +import java.util.concurrent.ThreadFactory; + +/** + * Callback interface that can be used to customize the {@link ThreadFactory} of the threads Testcontainers creates + * for its own use, such as the threads that check wait strategies, start containers in parallel or keep the + * connection to Ryuk open. + *

+ * Implementations are discovered via the Service Provider Interface (SPI) mechanism and must be registered in + * {@code META-INF/services/org.testcontainers.core.ThreadFactoryCustomizer}. + *

+ * Most of these threads belong to pools that are shared across the JVM and that create their threads lazily, on + * whichever thread happens to need one. A customizer lets tooling that tracks state per thread, such as a test + * framework that attributes output to the test that produced it, keep such state from leaking into these shared + * threads. + */ +public interface ThreadFactoryCustomizer { + /** + * Callback to customize a {@link ThreadFactory}. + * + * @param threadFactory the factory Testcontainers would otherwise use; it names the threads and makes them daemon threads + * @return the factory to use instead, typically one that delegates to {@code threadFactory} + */ + ThreadFactory customize(ThreadFactory threadFactory); +} diff --git a/core/src/main/java/org/testcontainers/images/TimeLimitedLoggedPullImageResultCallback.java b/core/src/main/java/org/testcontainers/images/TimeLimitedLoggedPullImageResultCallback.java index 88b8804dd8a..4337e6046e7 100644 --- a/core/src/main/java/org/testcontainers/images/TimeLimitedLoggedPullImageResultCallback.java +++ b/core/src/main/java/org/testcontainers/images/TimeLimitedLoggedPullImageResultCallback.java @@ -5,6 +5,7 @@ import org.slf4j.Logger; import org.testcontainers.DockerClientFactory; import org.testcontainers.utility.TestcontainersConfiguration; +import org.testcontainers.utility.ThreadFactoryCustomizers; import java.io.Closeable; import java.io.IOException; @@ -27,12 +28,12 @@ public class TimeLimitedLoggedPullImageResultCallback extends LoggedPullImageRes private static final ScheduledExecutorService PROGRESS_WATCHDOG_EXECUTOR = Executors.newScheduledThreadPool( 0, - runnable -> { + ThreadFactoryCustomizers.customize(runnable -> { Thread t = new Thread(DockerClientFactory.TESTCONTAINERS_THREAD_GROUP, runnable); t.setDaemon(true); t.setName("testcontainers-pull-watchdog-" + THREAD_ID.incrementAndGet()); return t; - } + }) ); private static final Duration PULL_PAUSE_TOLERANCE = Duration.ofSeconds( diff --git a/core/src/main/java/org/testcontainers/lifecycle/Startables.java b/core/src/main/java/org/testcontainers/lifecycle/Startables.java index d61919af346..5aadd4ce5d0 100644 --- a/core/src/main/java/org/testcontainers/lifecycle/Startables.java +++ b/core/src/main/java/org/testcontainers/lifecycle/Startables.java @@ -1,6 +1,7 @@ package org.testcontainers.lifecycle; import lombok.experimental.UtilityClass; +import org.testcontainers.utility.ThreadFactoryCustomizers; import java.util.Arrays; import java.util.Collection; @@ -18,16 +19,18 @@ public class Startables { private static final Executor EXECUTOR = Executors.newCachedThreadPool( - new ThreadFactory() { - private final AtomicLong COUNTER = new AtomicLong(0); + ThreadFactoryCustomizers.customize( + new ThreadFactory() { + private final AtomicLong COUNTER = new AtomicLong(0); - @Override - public Thread newThread(Runnable r) { - Thread thread = new Thread(r, "testcontainers-lifecycle-" + COUNTER.getAndIncrement()); - thread.setDaemon(true); - return thread; + @Override + public Thread newThread(Runnable r) { + Thread thread = new Thread(r, "testcontainers-lifecycle-" + COUNTER.getAndIncrement()); + thread.setDaemon(true); + return thread; + } } - } + ) ); /** diff --git a/core/src/main/java/org/testcontainers/utility/RyukResourceReaper.java b/core/src/main/java/org/testcontainers/utility/RyukResourceReaper.java index 999b1cbbffb..a62bef580fe 100644 --- a/core/src/main/java/org/testcontainers/utility/RyukResourceReaper.java +++ b/core/src/main/java/org/testcontainers/utility/RyukResourceReaper.java @@ -81,9 +81,11 @@ private synchronized void maybeStart() { String host = ryukContainer.getHost(); Integer ryukPort = ryukContainer.getFirstMappedPort(); - Thread kiraThread = new Thread( - DockerClientFactory.TESTCONTAINERS_THREAD_GROUP, - () -> { + Thread kiraThread = ThreadFactoryCustomizers + .customize(runnable -> { + return new Thread(DockerClientFactory.TESTCONTAINERS_THREAD_GROUP, runnable, "testcontainers-ryuk"); + }) + .newThread(() -> { while (true) { RYUK_ACK_RATE_LIMITER.doWhenReady(() -> { int index = 0; @@ -121,9 +123,7 @@ private synchronized void maybeStart() { } }); } - }, - "testcontainers-ryuk" - ); + }); kiraThread.setDaemon(true); kiraThread.start(); // We need to wait before we can start any containers to make sure that we delete them diff --git a/core/src/main/java/org/testcontainers/utility/ThreadFactoryCustomizers.java b/core/src/main/java/org/testcontainers/utility/ThreadFactoryCustomizers.java new file mode 100644 index 00000000000..a36cc83c327 --- /dev/null +++ b/core/src/main/java/org/testcontainers/utility/ThreadFactoryCustomizers.java @@ -0,0 +1,61 @@ +package org.testcontainers.utility; + +import lombok.extern.slf4j.Slf4j; +import org.testcontainers.UnstableAPI; +import org.testcontainers.core.ThreadFactoryCustomizer; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.ServiceLoader; +import java.util.concurrent.ThreadFactory; + +/** + * Applies the {@link ThreadFactoryCustomizer}s registered via SPI to the thread factories Testcontainers uses + * for its own threads. + */ +@UnstableAPI +@Slf4j +public final class ThreadFactoryCustomizers { + + private ThreadFactoryCustomizers() {} + + /** + * Returns {@code threadFactory} customized by every registered {@link ThreadFactoryCustomizer}, in the order + * they are found. A customizer that throws or returns {@code null} is skipped. + */ + public static ThreadFactory customize(ThreadFactory threadFactory) { + return customize(threadFactory, Holder.CUSTOMIZERS); + } + + static ThreadFactory customize(ThreadFactory threadFactory, Iterable customizers) { + ThreadFactory customized = threadFactory; + for (ThreadFactoryCustomizer customizer : customizers) { + try { + ThreadFactory next = customizer.customize(customized); + if (next != null) { + customized = next; + } else { + log.warn("Ignoring null ThreadFactory returned by {}", customizer.getClass().getName()); + } + } catch (Exception e) { + log.warn("Ignoring ThreadFactoryCustomizer {} that failed", customizer.getClass().getName(), e); + } + } + return customized; + } + + // loaded once, on first use, so that customizers are in place before the first shared pool is created + private static final class Holder { + + private static final List CUSTOMIZERS = load(); + + private static List load() { + List customizers = new ArrayList<>(); + for (ThreadFactoryCustomizer customizer : ServiceLoader.load(ThreadFactoryCustomizer.class)) { + customizers.add(customizer); + } + return Collections.unmodifiableList(customizers); + } + } +} diff --git a/core/src/test/java/org/testcontainers/containers/wait/strategy/AbstractWaitStrategyExecutorTest.java b/core/src/test/java/org/testcontainers/containers/wait/strategy/AbstractWaitStrategyExecutorTest.java new file mode 100644 index 00000000000..25dab4ff345 --- /dev/null +++ b/core/src/test/java/org/testcontainers/containers/wait/strategy/AbstractWaitStrategyExecutorTest.java @@ -0,0 +1,18 @@ +package org.testcontainers.containers.wait.strategy; + +import org.junit.jupiter.api.Test; +import org.testcontainers.custom.TestThreadFactoryCustomizer; + +import static org.assertj.core.api.Assertions.assertThat; + +class AbstractWaitStrategyExecutorTest { + + @Test + void waitStrategyThreadsAreCreatedByTheCustomizedFactory() throws Exception { + Thread thread = AbstractWaitStrategy.EXECUTOR.submit(Thread::currentThread).get(); + + assertThat(thread.getName()).startsWith("testcontainers-wait-"); + assertThat(thread.isDaemon()).isTrue(); + assertThat(TestThreadFactoryCustomizer.CREATED).contains(thread); + } +} diff --git a/core/src/test/java/org/testcontainers/custom/TestThreadFactoryCustomizer.java b/core/src/test/java/org/testcontainers/custom/TestThreadFactoryCustomizer.java new file mode 100644 index 00000000000..cbe5d8c505c --- /dev/null +++ b/core/src/test/java/org/testcontainers/custom/TestThreadFactoryCustomizer.java @@ -0,0 +1,24 @@ +package org.testcontainers.custom; + +import org.testcontainers.core.ThreadFactoryCustomizer; + +import java.util.Collections; +import java.util.Set; +import java.util.WeakHashMap; +import java.util.concurrent.ThreadFactory; + +public class TestThreadFactoryCustomizer implements ThreadFactoryCustomizer { + + public static final Set CREATED = Collections.synchronizedSet( + Collections.newSetFromMap(new WeakHashMap<>()) + ); + + @Override + public ThreadFactory customize(ThreadFactory threadFactory) { + return runnable -> { + Thread thread = threadFactory.newThread(runnable); + CREATED.add(thread); + return thread; + }; + } +} diff --git a/core/src/test/java/org/testcontainers/utility/ThreadFactoryCustomizersTest.java b/core/src/test/java/org/testcontainers/utility/ThreadFactoryCustomizersTest.java new file mode 100644 index 00000000000..2db78f64637 --- /dev/null +++ b/core/src/test/java/org/testcontainers/utility/ThreadFactoryCustomizersTest.java @@ -0,0 +1,64 @@ +package org.testcontainers.utility; + +import org.junit.jupiter.api.Test; +import org.testcontainers.core.ThreadFactoryCustomizer; +import org.testcontainers.custom.TestThreadFactoryCustomizer; +import org.testcontainers.lifecycle.Startable; +import org.testcontainers.lifecycle.Startables; + +import java.util.Arrays; +import java.util.Collections; +import java.util.concurrent.ThreadFactory; +import java.util.concurrent.atomic.AtomicReference; + +import static org.assertj.core.api.Assertions.assertThat; + +class ThreadFactoryCustomizersTest { + + @Test + void appliesRegisteredCustomizersToSharedPools() { + AtomicReference startedOn = new AtomicReference<>(); + Startable startable = new Startable() { + @Override + public void start() { + startedOn.set(Thread.currentThread()); + } + + @Override + public void stop() {} + }; + + Startables.deepStart(startable).join(); + + assertThat(startedOn.get().getName()).startsWith("testcontainers-lifecycle-"); + assertThat(TestThreadFactoryCustomizer.CREATED).contains(startedOn.get()); + } + + @Test + void appliesCustomizersInOrder() { + ThreadFactory base = runnable -> new Thread(runnable, "base"); + ThreadFactoryCustomizer first = factory -> runnable -> rename(factory.newThread(runnable), "-first"); + ThreadFactoryCustomizer second = factory -> runnable -> rename(factory.newThread(runnable), "-second"); + + Thread thread = ThreadFactoryCustomizers.customize(base, Arrays.asList(first, second)).newThread(() -> {}); + + assertThat(thread.getName()).isEqualTo("base-first-second"); + } + + @Test + void skipsCustomizersThatFailOrReturnNull() { + ThreadFactory base = runnable -> new Thread(runnable, "base"); + ThreadFactoryCustomizer failing = factory -> { + throw new IllegalStateException("boom"); + }; + ThreadFactoryCustomizer returningNull = factory -> null; + + assertThat(ThreadFactoryCustomizers.customize(base, Arrays.asList(failing, returningNull))).isSameAs(base); + assertThat(ThreadFactoryCustomizers.customize(base, Collections.emptyList())).isSameAs(base); + } + + private static Thread rename(Thread thread, String suffix) { + thread.setName(thread.getName() + suffix); + return thread; + } +} diff --git a/core/src/test/resources/META-INF/services/org.testcontainers.core.ThreadFactoryCustomizer b/core/src/test/resources/META-INF/services/org.testcontainers.core.ThreadFactoryCustomizer new file mode 100644 index 00000000000..087ee96f35b --- /dev/null +++ b/core/src/test/resources/META-INF/services/org.testcontainers.core.ThreadFactoryCustomizer @@ -0,0 +1 @@ +org.testcontainers.custom.TestThreadFactoryCustomizer diff --git a/docs/features/advanced_options.md b/docs/features/advanced_options.md index e979da9ecdf..ebca065b45f 100644 --- a/docs/features/advanced_options.md +++ b/docs/features/advanced_options.md @@ -86,6 +86,27 @@ The previous implementation should be registered in `META-INF/services/org.testc !!! warning `CreateContainerCmdModifier` implementation will apply to all containers created by Testcontainers. +## Customizing Testcontainers' own threads + +Testcontainers runs some of its work on threads it creates itself, such as the threads that check wait strategies, +start containers in parallel with `Startables.deepStart`, watch image pulls, or keep the connection to Ryuk open. +Most of them belong to pools that are shared by the whole JVM and that create their threads lazily. + +Tools that track state per thread, such as a test framework that attributes output to the test that produced it, +can customize how these threads are created with a `ThreadFactoryCustomizer`, via the Service Provider Interface (SPI) mechanism. +The customizer receives the factory Testcontainers would otherwise use, and returns the factory to use instead. + + +[ThreadFactoryCustomizer example implementation](../../core/src/test/java/org/testcontainers/custom/TestThreadFactoryCustomizer.java) + + +The previous implementation should be registered in `META-INF/services/org.testcontainers.core.ThreadFactoryCustomizer` file. + +!!! warning + A `ThreadFactoryCustomizer` applies to every thread pool Testcontainers creates for its own use, and is loaded once, + when the first of them is created. The factory it returns should delegate to the one it receives, + so that the threads keep their names and remain daemon threads. + ## Parallel Container Startup Usually, containers are started sequentially when more than one container is used. diff --git a/modules/r2dbc/src/main/java/org/testcontainers/r2dbc/TestcontainersR2DBCConnectionFactory.java b/modules/r2dbc/src/main/java/org/testcontainers/r2dbc/TestcontainersR2DBCConnectionFactory.java index bada076eec9..f0843c9ba3f 100644 --- a/modules/r2dbc/src/main/java/org/testcontainers/r2dbc/TestcontainersR2DBCConnectionFactory.java +++ b/modules/r2dbc/src/main/java/org/testcontainers/r2dbc/TestcontainersR2DBCConnectionFactory.java @@ -8,6 +8,7 @@ import io.r2dbc.spi.ConnectionFactoryOptions; import org.reactivestreams.Publisher; import org.testcontainers.lifecycle.Startable; +import org.testcontainers.utility.ThreadFactoryCustomizers; import java.util.ServiceLoader; import java.util.concurrent.CompletableFuture; @@ -20,12 +21,14 @@ class TestcontainersR2DBCConnectionFactory implements ConnectionFactory, Closeab private static final AtomicLong THREAD_COUNT = new AtomicLong(); - private static final Executor EXECUTOR = Executors.newCachedThreadPool(r -> { - Thread thread = new Thread(r); - thread.setName("testcontainers-r2dbc-" + THREAD_COUNT.getAndIncrement()); - thread.setDaemon(true); - return thread; - }); + private static final Executor EXECUTOR = Executors.newCachedThreadPool( + ThreadFactoryCustomizers.customize(r -> { + Thread thread = new Thread(r); + thread.setName("testcontainers-r2dbc-" + THREAD_COUNT.getAndIncrement()); + thread.setDaemon(true); + return thread; + }) + ); private final ConnectionFactoryOptions options; From 00b29e88ee94322a09e87a4bd5e426e208e9e3d0 Mon Sep 17 00:00:00 2001 From: Matthew de Detrich Date: Sun, 29 Nov 2026 22:30:55 +0100 Subject: [PATCH 2/4] Tolerate ServiceLoader errors when loading ThreadFactoryCustomizers A provider that fails to load made ServiceLoader throw a ServiceConfigurationError from the Holder's static initializer, so every pool that uses ThreadFactoryCustomizers would then fail with NoClassDefFoundError. Skip such a provider with a warning, and stop with the providers loaded so far if the configuration can't be read further. Also name the threads the SPI applies to in the docs and Javadoc, and say that duct-tape's and docker-java's threads aren't covered. Co-Authored-By: Claude Opus 5.5 --- .../core/ThreadFactoryCustomizer.java | 7 ++-- .../utility/ThreadFactoryCustomizers.java | 41 +++++++++++++++---- .../utility/ThreadFactoryCustomizersTest.java | 35 ++++++++++++++++ docs/features/advanced_options.md | 18 ++++++-- 4 files changed, 85 insertions(+), 16 deletions(-) diff --git a/core/src/main/java/org/testcontainers/core/ThreadFactoryCustomizer.java b/core/src/main/java/org/testcontainers/core/ThreadFactoryCustomizer.java index a95352bada9..bc9e910b3e6 100644 --- a/core/src/main/java/org/testcontainers/core/ThreadFactoryCustomizer.java +++ b/core/src/main/java/org/testcontainers/core/ThreadFactoryCustomizer.java @@ -3,9 +3,10 @@ import java.util.concurrent.ThreadFactory; /** - * Callback interface that can be used to customize the {@link ThreadFactory} of the threads Testcontainers creates - * for its own use, such as the threads that check wait strategies, start containers in parallel or keep the - * connection to Ryuk open. + * Callback interface that can be used to customize the {@link ThreadFactory} of threads Testcontainers creates + * for its own use: the threads that run wait strategy port checks, start containers in parallel, watch image pulls, + * keep the connection to Ryuk open, or start containers for the R2DBC module. Threads created by the + * {@code duct-tape} library, and by {@code docker-java} for streaming calls, are not covered. *

* Implementations are discovered via the Service Provider Interface (SPI) mechanism and must be registered in * {@code META-INF/services/org.testcontainers.core.ThreadFactoryCustomizer}. diff --git a/core/src/main/java/org/testcontainers/utility/ThreadFactoryCustomizers.java b/core/src/main/java/org/testcontainers/utility/ThreadFactoryCustomizers.java index a36cc83c327..0fe50d88a88 100644 --- a/core/src/main/java/org/testcontainers/utility/ThreadFactoryCustomizers.java +++ b/core/src/main/java/org/testcontainers/utility/ThreadFactoryCustomizers.java @@ -6,7 +6,9 @@ import java.util.ArrayList; import java.util.Collections; +import java.util.Iterator; import java.util.List; +import java.util.ServiceConfigurationError; import java.util.ServiceLoader; import java.util.concurrent.ThreadFactory; @@ -45,17 +47,38 @@ static ThreadFactory customize(ThreadFactory threadFactory, Iterable load(Iterator providers) { + List customizers = new ArrayList<>(); + while (true) { + try { + if (!providers.hasNext()) { + break; + } + } catch (ServiceConfigurationError e) { + // the provider configuration can't be read any further, and retrying may fail the same way + log.warn("Stopped loading ThreadFactoryCustomizers after an error", e); + break; + } + try { + customizers.add(providers.next()); + } catch (ServiceConfigurationError e) { + // this provider is skipped; the iterator has moved past it, so the next one can still be loaded + log.warn("Ignoring ThreadFactoryCustomizer that could not be loaded", e); + } + } + return Collections.unmodifiableList(customizers); + } + // loaded once, on first use, so that customizers are in place before the first shared pool is created private static final class Holder { - private static final List CUSTOMIZERS = load(); - - private static List load() { - List customizers = new ArrayList<>(); - for (ThreadFactoryCustomizer customizer : ServiceLoader.load(ThreadFactoryCustomizer.class)) { - customizers.add(customizer); - } - return Collections.unmodifiableList(customizers); - } + private static final List CUSTOMIZERS = load( + ServiceLoader.load(ThreadFactoryCustomizer.class).iterator() + ); } } diff --git a/core/src/test/java/org/testcontainers/utility/ThreadFactoryCustomizersTest.java b/core/src/test/java/org/testcontainers/utility/ThreadFactoryCustomizersTest.java index 2db78f64637..ed77472a189 100644 --- a/core/src/test/java/org/testcontainers/utility/ThreadFactoryCustomizersTest.java +++ b/core/src/test/java/org/testcontainers/utility/ThreadFactoryCustomizersTest.java @@ -8,6 +8,8 @@ import java.util.Arrays; import java.util.Collections; +import java.util.Iterator; +import java.util.ServiceConfigurationError; import java.util.concurrent.ThreadFactory; import java.util.concurrent.atomic.AtomicReference; @@ -57,6 +59,39 @@ void skipsCustomizersThatFailOrReturnNull() { assertThat(ThreadFactoryCustomizers.customize(base, Collections.emptyList())).isSameAs(base); } + @Test + void skipsProvidersThatCannotBeLoaded() { + ThreadFactoryCustomizer first = factory -> factory; + ThreadFactoryCustomizer third = factory -> factory; + // a provider that fails to load, then one that loads, then a provider configuration that can't be read + Iterator providers = new Iterator() { + private int position = 0; + + @Override + public boolean hasNext() { + if (position == 3) { + throw new ServiceConfigurationError("unreadable provider configuration"); + } + return true; + } + + @Override + public ThreadFactoryCustomizer next() { + position++; + switch (position) { + case 1: + return first; + case 2: + throw new ServiceConfigurationError("provider could not be instantiated"); + default: + return third; + } + } + }; + + assertThat(ThreadFactoryCustomizers.load(providers)).containsExactly(first, third); + } + private static Thread rename(Thread thread, String suffix) { thread.setName(thread.getName() + suffix); return thread; diff --git a/docs/features/advanced_options.md b/docs/features/advanced_options.md index ebca065b45f..a25e8c6c4d7 100644 --- a/docs/features/advanced_options.md +++ b/docs/features/advanced_options.md @@ -88,13 +88,23 @@ The previous implementation should be registered in `META-INF/services/org.testc ## Customizing Testcontainers' own threads -Testcontainers runs some of its work on threads it creates itself, such as the threads that check wait strategies, -start containers in parallel with `Startables.deepStart`, watch image pulls, or keep the connection to Ryuk open. -Most of them belong to pools that are shared by the whole JVM and that create their threads lazily. +Testcontainers runs some of its work on threads it creates itself. Most of them belong to pools that are shared by +the whole JVM and that create their threads lazily. Tools that track state per thread, such as a test framework that attributes output to the test that produced it, can customize how these threads are created with a `ThreadFactoryCustomizer`, via the Service Provider Interface (SPI) mechanism. The customizer receives the factory Testcontainers would otherwise use, and returns the factory to use instead. +It applies to the threads that: + +* run port checks for wait strategies (`testcontainers-wait-*`) +* start containers in parallel with `Startables.deepStart` (`testcontainers-lifecycle-*`) +* watch image pulls (`testcontainers-pull-watchdog-*`) +* keep the connection to Ryuk open (`testcontainers-ryuk`) +* start containers for the R2DBC module (`testcontainers-r2dbc-*`) + +It does not apply to the threads of the `duct-tape` library (`ducttape-*`), on which most wait strategies and startup +checks run their retries with a timeout, nor to the threads `docker-java` starts for streaming calls, such as following +a container's logs. [ThreadFactoryCustomizer example implementation](../../core/src/test/java/org/testcontainers/custom/TestThreadFactoryCustomizer.java) @@ -103,7 +113,7 @@ The customizer receives the factory Testcontainers would otherwise use, and retu The previous implementation should be registered in `META-INF/services/org.testcontainers.core.ThreadFactoryCustomizer` file. !!! warning - A `ThreadFactoryCustomizer` applies to every thread pool Testcontainers creates for its own use, and is loaded once, + A `ThreadFactoryCustomizer` applies to all of the threads listed above, and is loaded once, when the first of them is created. The factory it returns should delegate to the one it receives, so that the threads keep their names and remain daemon threads. From 7976e133b17d89718bd3288b6f3704026c511de7 Mon Sep 17 00:00:00 2001 From: Matthew de Detrich Date: Sun, 29 Nov 2026 22:53:41 +0100 Subject: [PATCH 3/4] Stop loading ThreadFactoryCustomizers at the first ServiceLoader error ServiceLoader doesn't guarantee that its iterator moves past a provider that failed to load, so skipping it and continuing could retry the same provider forever. Stop at the first error instead, keeping the customizers loaded before it. Co-Authored-By: Claude Opus 5.5 --- .../utility/ThreadFactoryCustomizers.java | 29 ++++---- .../utility/ThreadFactoryCustomizersTest.java | 68 ++++++++++++++----- 2 files changed, 64 insertions(+), 33 deletions(-) diff --git a/core/src/main/java/org/testcontainers/utility/ThreadFactoryCustomizers.java b/core/src/main/java/org/testcontainers/utility/ThreadFactoryCustomizers.java index 0fe50d88a88..d45d69289e2 100644 --- a/core/src/main/java/org/testcontainers/utility/ThreadFactoryCustomizers.java +++ b/core/src/main/java/org/testcontainers/utility/ThreadFactoryCustomizers.java @@ -48,28 +48,23 @@ static ThreadFactory customize(ThreadFactory threadFactory, Iterable load(Iterator providers) { List customizers = new ArrayList<>(); - while (true) { - try { - if (!providers.hasNext()) { - break; - } - } catch (ServiceConfigurationError e) { - // the provider configuration can't be read any further, and retrying may fail the same way - log.warn("Stopped loading ThreadFactoryCustomizers after an error", e); - break; - } - try { + try { + while (providers.hasNext()) { customizers.add(providers.next()); - } catch (ServiceConfigurationError e) { - // this provider is skipped; the iterator has moved past it, so the next one can still be loaded - log.warn("Ignoring ThreadFactoryCustomizer that could not be loaded", e); } + } catch (ServiceConfigurationError e) { + log.warn( + "Stopped loading ThreadFactoryCustomizers after an error, keeping the {} loaded", + customizers.size(), + e + ); } return Collections.unmodifiableList(customizers); } diff --git a/core/src/test/java/org/testcontainers/utility/ThreadFactoryCustomizersTest.java b/core/src/test/java/org/testcontainers/utility/ThreadFactoryCustomizersTest.java index ed77472a189..cfeeb1efb72 100644 --- a/core/src/test/java/org/testcontainers/utility/ThreadFactoryCustomizersTest.java +++ b/core/src/test/java/org/testcontainers/utility/ThreadFactoryCustomizersTest.java @@ -11,7 +11,9 @@ import java.util.Iterator; import java.util.ServiceConfigurationError; import java.util.concurrent.ThreadFactory; +import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Supplier; import static org.assertj.core.api.Assertions.assertThat; @@ -60,16 +62,57 @@ void skipsCustomizersThatFailOrReturnNull() { } @Test - void skipsProvidersThatCannotBeLoaded() { - ThreadFactoryCustomizer first = factory -> factory; - ThreadFactoryCustomizer third = factory -> factory; - // a provider that fails to load, then one that loads, then a provider configuration that can't be read + void stopsAtAProviderThatCannotBeLoaded() { + ThreadFactoryCustomizer loaded = factory -> factory; + ThreadFactoryCustomizer afterTheError = factory -> factory; + Iterator providers = Arrays + .>asList( + () -> loaded, + () -> { + throw new ServiceConfigurationError("provider could not be instantiated"); + }, + () -> afterTheError + ) + .stream() + .map(Supplier::get) + .iterator(); + + assertThat(ThreadFactoryCustomizers.load(providers)).containsExactly(loaded); + } + + @Test + void doesNotRetryAProviderAfterAnError() { + // an iterator that never moves past the failing provider, which ServiceLoader's contract allows; + // a retry fails the test immediately, since load only catches ServiceConfigurationError + AtomicInteger attempts = new AtomicInteger(); Iterator providers = new Iterator() { - private int position = 0; + @Override + public boolean hasNext() { + return true; + } + + @Override + public ThreadFactoryCustomizer next() { + if (attempts.incrementAndGet() > 1) { + throw new AssertionError("retried the failing provider"); + } + throw new ServiceConfigurationError("provider could not be instantiated"); + } + }; + + assertThat(ThreadFactoryCustomizers.load(providers)).isEmpty(); + assertThat(attempts).hasValue(1); + } + + @Test + void stopsWhenTheProvidersCannotBeListed() { + ThreadFactoryCustomizer loaded = factory -> factory; + Iterator providers = new Iterator() { + private boolean returned = false; @Override public boolean hasNext() { - if (position == 3) { + if (returned) { throw new ServiceConfigurationError("unreadable provider configuration"); } return true; @@ -77,19 +120,12 @@ public boolean hasNext() { @Override public ThreadFactoryCustomizer next() { - position++; - switch (position) { - case 1: - return first; - case 2: - throw new ServiceConfigurationError("provider could not be instantiated"); - default: - return third; - } + returned = true; + return loaded; } }; - assertThat(ThreadFactoryCustomizers.load(providers)).containsExactly(first, third); + assertThat(ThreadFactoryCustomizers.load(providers)).containsExactly(loaded); } private static Thread rename(Thread thread, String suffix) { From 750004634010504275bde1f1fe16ca72633660d5 Mon Sep 17 00:00:00 2001 From: Matthew de Detrich Date: Sun, 29 Nov 2026 23:02:37 +0100 Subject: [PATCH 4/4] Handle provider linkage failures when loading ThreadFactoryCustomizers A provider that can't be linked, for example because its superclass is missing, makes ServiceLoader throw a LinkageError such as NoClassDefFoundError rather than a ServiceConfigurationError: from next() on Java 8, and from hasNext() on later versions, which load provider classes ahead of time. That escaped the Holder initializer. Handle it like a ServiceConfigurationError, and also skip a customizer whose customize method fails with a LinkageError. Co-Authored-By: Claude Opus 5.5 --- .../utility/ThreadFactoryCustomizers.java | 12 +++-- .../utility/ThreadFactoryCustomizersTest.java | 53 +++++++++++++++++++ 2 files changed, 61 insertions(+), 4 deletions(-) diff --git a/core/src/main/java/org/testcontainers/utility/ThreadFactoryCustomizers.java b/core/src/main/java/org/testcontainers/utility/ThreadFactoryCustomizers.java index d45d69289e2..2d87ea2169c 100644 --- a/core/src/main/java/org/testcontainers/utility/ThreadFactoryCustomizers.java +++ b/core/src/main/java/org/testcontainers/utility/ThreadFactoryCustomizers.java @@ -24,7 +24,8 @@ private ThreadFactoryCustomizers() {} /** * Returns {@code threadFactory} customized by every registered {@link ThreadFactoryCustomizer}, in the order - * they are found. A customizer that throws or returns {@code null} is skipped. + * they are found. A customizer that throws, including a {@link LinkageError} such as a missing class, or returns + * {@code null} is skipped. */ public static ThreadFactory customize(ThreadFactory threadFactory) { return customize(threadFactory, Holder.CUSTOMIZERS); @@ -40,7 +41,7 @@ static ThreadFactory customize(ThreadFactory threadFactory, Iterable load(Iterator providers) { List customizers = new ArrayList<>(); @@ -59,7 +63,7 @@ static List load(Iterator prov while (providers.hasNext()) { customizers.add(providers.next()); } - } catch (ServiceConfigurationError e) { + } catch (ServiceConfigurationError | LinkageError e) { log.warn( "Stopped loading ThreadFactoryCustomizers after an error, keeping the {} loaded", customizers.size(), diff --git a/core/src/test/java/org/testcontainers/utility/ThreadFactoryCustomizersTest.java b/core/src/test/java/org/testcontainers/utility/ThreadFactoryCustomizersTest.java index cfeeb1efb72..634fdb9b47e 100644 --- a/core/src/test/java/org/testcontainers/utility/ThreadFactoryCustomizersTest.java +++ b/core/src/test/java/org/testcontainers/utility/ThreadFactoryCustomizersTest.java @@ -128,6 +128,59 @@ public ThreadFactoryCustomizer next() { assertThat(ThreadFactoryCustomizers.load(providers)).containsExactly(loaded); } + @Test + void stopsWhenAProviderCannotBeLinkedInNext() { + // Java 8's ServiceLoader lets a provider's linkage failure, such as a missing superclass, escape from next() + ThreadFactoryCustomizer loaded = factory -> factory; + Iterator providers = Arrays + .>asList( + () -> loaded, + () -> { + throw new NoClassDefFoundError("com/example/MissingSuperclass"); + } + ) + .stream() + .map(Supplier::get) + .iterator(); + + assertThat(ThreadFactoryCustomizers.load(providers)).containsExactly(loaded); + } + + @Test + void stopsWhenAProviderCannotBeLinkedInHasNext() { + // later versions load the provider class ahead of time, so the same failure escapes from hasNext() + ThreadFactoryCustomizer loaded = factory -> factory; + Iterator providers = new Iterator() { + private boolean returned = false; + + @Override + public boolean hasNext() { + if (returned) { + throw new NoClassDefFoundError("com/example/MissingSuperclass"); + } + return true; + } + + @Override + public ThreadFactoryCustomizer next() { + returned = true; + return loaded; + } + }; + + assertThat(ThreadFactoryCustomizers.load(providers)).containsExactly(loaded); + } + + @Test + void skipsCustomizersThatCannotBeLinked() { + ThreadFactory base = runnable -> new Thread(runnable, "base"); + ThreadFactoryCustomizer unlinkable = factory -> { + throw new NoClassDefFoundError("com/example/MissingDependency"); + }; + + assertThat(ThreadFactoryCustomizers.customize(base, Collections.singletonList(unlinkable))).isSameAs(base); + } + private static Thread rename(Thread thread, String suffix) { thread.setName(thread.getName() + suffix); return thread;