Skip to content

Commit

Permalink
Improve leak detector to wait for threads to terminate when a differe…
Browse files Browse the repository at this point in the history
…nce is detected
  • Loading branch information
lhotari committed Oct 17, 2023
1 parent ccf8e57 commit 1d411d1
Showing 1 changed file with 12 additions and 6 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
import java.util.Set;
import java.util.stream.Collectors;
import org.apache.commons.lang3.ThreadUtils;
import org.apache.commons.lang3.mutable.MutableBoolean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

Expand All @@ -41,23 +42,25 @@ public class ThreadLeakDetectorListener extends BetweenTestClassesListenerAdapte
@Override
protected void onBetweenTestClasses(Class<?> endedTestClass, Class<?> startedTestClass) {
LOG.info("Capturing identifiers of running threads.");
MutableBoolean differenceDetected = new MutableBoolean();
Set<ThreadKey> currentThreadKeys =
compareThreads(capturedThreadKeys, endedTestClass, WAIT_FOR_THREAD_TERMINATION_MILLIS <= 0);
if (WAIT_FOR_THREAD_TERMINATION_MILLIS > 0 && capturedThreadKeys != null
&& currentThreadKeys.size() > capturedThreadKeys.size()) {
LOG.info("Waiting {} ms for threads to terminate.", WAIT_FOR_THREAD_TERMINATION_MILLIS);
compareThreads(capturedThreadKeys, endedTestClass, WAIT_FOR_THREAD_TERMINATION_MILLIS <= 0,
differenceDetected);
if (WAIT_FOR_THREAD_TERMINATION_MILLIS > 0 && differenceDetected.booleanValue()) {
LOG.info("Difference detected in active threads. Waiting {} ms for threads to terminate.",
WAIT_FOR_THREAD_TERMINATION_MILLIS);
try {
Thread.sleep(WAIT_FOR_THREAD_TERMINATION_MILLIS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
currentThreadKeys = compareThreads(capturedThreadKeys, endedTestClass, true);
currentThreadKeys = compareThreads(capturedThreadKeys, endedTestClass, true, null);
}
capturedThreadKeys = currentThreadKeys;
}

private static Set<ThreadKey> compareThreads(Set<ThreadKey> previousThreadKeys, Class<?> endedTestClass,
boolean logDifference) {
boolean logDifference, MutableBoolean differenceDetected) {
Set<ThreadKey> threadKeys = Collections.unmodifiableSet(ThreadUtils.getAllThreads().stream()
.map(ThreadKey::of)
.collect(Collectors.<ThreadKey, Set<ThreadKey>>toCollection(LinkedHashSet::new)));
Expand All @@ -67,6 +70,9 @@ private static Set<ThreadKey> compareThreads(Set<ThreadKey> previousThreadKeys,
for (ThreadKey threadKey : threadKeys) {
if (!previousThreadKeys.contains(threadKey)) {
newThreadsCounter++;
if (differenceDetected != null) {
differenceDetected.setTrue();
}
if (logDifference) {
LOG.warn("Tests in class {} created thread id {} with name '{}'",
endedTestClass.getSimpleName(),
Expand Down

0 comments on commit 1d411d1

Please sign in to comment.