@@ -88,6 +88,8 @@ public class PutMediaClientWithFilesTest {
8888 private KinesisVideoStreamResource kinesisVideoStreamResource ;
8989 private final InputStream testMkvFile ;
9090 private final List <String > expectedAcks ;
91+ private static final int SHUTDOWN_TIMEOUT_MS = 5000 ; //total time allowed for clean up
92+ private static final int INTERVAL_MS = 100 ; //time interval between each clean up
9193
9294 @ Before
9395 public void setUp () throws Exception {
@@ -312,13 +314,43 @@ public void accept(final Exception exception) {
312314 // Thread leak detection
313315 // Compares thread state before/after to ensure no background threads
314316 // are leaked by the PutMediaClient implementation
315- final List <String > threadsAfter = Thread .getAllStackTraces ().keySet ()
316- .stream ()
317- .map (Thread ::getName )
318- .collect (Collectors .toList ());
319317
320318 threadsBefore .sort (String .CASE_INSENSITIVE_ORDER );
321- threadsAfter .sort (String .CASE_INSENSITIVE_ORDER );
322- assertEquals ("There was a thread that wasn't cleaned up properly!" , threadsBefore , threadsAfter );
319+
320+
321+ for (int i = 0 ; i < SHUTDOWN_TIMEOUT_MS ; i += INTERVAL_MS ) {
322+ final List <String > threadsNow = Thread .getAllStackTraces ().keySet ()
323+ .stream ()
324+ .map (Thread ::getName )
325+ .collect (Collectors .toList ());
326+
327+ threadsNow .sort (String .CASE_INSENSITIVE_ORDER );
328+ log .info ("Cleanup iteration {}/() ms - Current thread count: {}, Expected: {}" ,
329+ i , SHUTDOWN_TIMEOUT_MS , threadsNow .size (), threadsBefore .size ());
330+
331+ if (threadsNow .equals (threadsBefore )) {
332+ break ; // threads are cleaned up
333+ } else {
334+ //if threads are not clearned up yet
335+ List <String > extraThreads = new ArrayList <>(threadsNow );
336+ extraThreads .removeAll (threadsBefore );
337+ if (!extraThreads .isEmpty ()) {
338+ log .warn ("extra threads are still running: {}" , extraThreads );
339+ }
340+ }
341+
342+ if (i + INTERVAL_MS >= SHUTDOWN_TIMEOUT_MS ) {
343+ //time has exceeded shutdown timeout
344+ log .error ("Expected threads: {}" , threadsBefore );
345+ log .error ("Current threads: {}" , threadsNow );
346+ fail ("Timeout waiting for threads to be cleaned up properly" );
347+ }
348+
349+ try {
350+ Thread .sleep (INTERVAL_MS );
351+ } catch (InterruptedException e ) {
352+ Thread .currentThread ().interrupt ();
353+ }
354+ }
323355 }
324356}
0 commit comments