Skip to content

Commit

Permalink
Ignore threads created by Testcontainers
Browse files Browse the repository at this point in the history
  • Loading branch information
lhotari committed Nov 1, 2023
1 parent 2daace5 commit 076fd55
Showing 1 changed file with 30 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Field;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Collections;
Expand Down Expand Up @@ -56,6 +57,17 @@ public class ThreadLeakDetectorListener extends BetweenTestClassesListenerAdapte

private Set<ThreadKey> capturedThreadKeys;

private static final Field THREAD_TARGET_FIELD;
static {
Field targetField = null;
try {
targetField = Thread.class.getDeclaredField("target");
targetField.setAccessible(true);
} catch (NoSuchFieldException e) {
LOG.warn("Cannot find target field in Thread.class", e);
}
THREAD_TARGET_FIELD = targetField;
}

@Override
protected void onBetweenTestClasses(Class<?> endedTestClass, Class<?> startedTestClass) {
Expand Down Expand Up @@ -206,9 +218,27 @@ private static boolean shouldSkipThread(Thread thread) {
return true;
}
}
Runnable target = extractRunnableTarget(thread);
if (target != null) {
String targetClassName = target.getClass().getName();
// ignore threads that contain a Runnable class under org.testcontainers package
if (targetClassName.startsWith("org.testcontainers.")) {
return true;
}
}
return false;
}

private static Runnable extractRunnableTarget(Thread thread) {
Runnable target = null;
try {
target = (Runnable) THREAD_TARGET_FIELD.get(thread);
} catch (IllegalAccessException e) {
LOG.warn("Cannot access target field in Thread.class", e);
}
return target;
}

/**
* Unique key for a thread
* Based on thread id and it's identity hash code
Expand Down

0 comments on commit 076fd55

Please sign in to comment.