Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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
Expand Down
Original file line number Diff line number Diff line change
@@ -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.
* <p>
* Implementations are discovered via the Service Provider Interface (SPI) mechanism and must be registered in
* {@code META-INF/services/org.testcontainers.core.ThreadFactoryCustomizer}.
* <p>
* 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);
}
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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(
Expand Down
19 changes: 11 additions & 8 deletions core/src/main/java/org/testcontainers/lifecycle/Startables.java
Original file line number Diff line number Diff line change
@@ -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;
Expand All @@ -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;
}
}
}
)
);

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
@@ -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<ThreadFactoryCustomizer> 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<ThreadFactoryCustomizer> CUSTOMIZERS = load();

private static List<ThreadFactoryCustomizer> load() {
List<ThreadFactoryCustomizer> customizers = new ArrayList<>();
for (ThreadFactoryCustomizer customizer : ServiceLoader.load(ThreadFactoryCustomizer.class)) {
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
customizers.add(customizer);
}
return Collections.unmodifiableList(customizers);
}
}
}
Original file line number Diff line number Diff line change
@@ -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);
}
}
Original file line number Diff line number Diff line change
@@ -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<Thread> 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;
};
}
}
Original file line number Diff line number Diff line change
@@ -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<Thread> 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;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
org.testcontainers.custom.TestThreadFactoryCustomizer
21 changes: 21 additions & 0 deletions docs/features/advanced_options.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

<!--codeinclude-->
[ThreadFactoryCustomizer example implementation](../../core/src/test/java/org/testcontainers/custom/TestThreadFactoryCustomizer.java)
<!--/codeinclude-->

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,
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
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.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;

Expand Down
Loading