Bug 536811 - ThreadNameChangeTests failed with No value present

Its possible that ThreadNameChangeTests attempts to retrieve a thread
necessary for the test, before JDIDebugTarget.ThreadStartHandler has
added this thread to the set of threads in JDIDebugTarget.

This change adds a timeout of five seconds to the test, to allow
processing in ThreadStartHandler to finish in a reasonable time span.

Change-Id: Ia481c77932536379c70196e450cd7d59e71c1195
Signed-off-by: Simeon Andreev <simeon.danailov.andreev@gmail.com>
diff --git a/org.eclipse.jdt.debug.tests/tests/org/eclipse/jdt/debug/tests/breakpoints/ThreadNameChangeTests.java b/org.eclipse.jdt.debug.tests/tests/org/eclipse/jdt/debug/tests/breakpoints/ThreadNameChangeTests.java
index d40f7a7..53d1bcc 100644
--- a/org.eclipse.jdt.debug.tests/tests/org/eclipse/jdt/debug/tests/breakpoints/ThreadNameChangeTests.java
+++ b/org.eclipse.jdt.debug.tests/tests/org/eclipse/jdt/debug/tests/breakpoints/ThreadNameChangeTests.java
@@ -13,7 +13,9 @@
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.List;
+import java.util.Optional;
 import java.util.concurrent.atomic.AtomicReference;
+import java.util.function.Predicate;
 import java.util.stream.Collectors;
 import java.util.stream.Stream;
 
@@ -155,15 +157,32 @@
 	}
 
 	private IThread findThread(IJavaThread thread, String name) throws DebugException {
-		IThread t = Arrays.stream(thread.getDebugTarget().getThreads()).filter(x -> {
+		return findThread(thread, name, 5_000);
+	}
+
+	private IThread findThread(IJavaThread thread, String name, long timeout) throws DebugException {
+		Predicate<IThread> predicate = x -> {
 			try {
 				return x.getName().equals(name);
 			}
 			catch (DebugException e1) {
 			}
 			return false;
-		}).findFirst().get();
-		return t;
+		};
+		IThread[] threads = {};
+
+		// Wait until timeout or JDIDebugTarget.ThreadStartHandler has added the thread.
+		long start = System.currentTimeMillis();
+		while (System.currentTimeMillis() - start <= timeout) {
+			threads = thread.getDebugTarget().getThreads();
+			Optional<IThread> match = Arrays.stream(threads).filter(predicate).findFirst();
+			if (match.isPresent()) {
+				return match.get();
+			}
+		}
+
+		throw new AssertionError("Timeout of " + timeout + "ms reached, thread with name \"" + name + "\" not found in set of threads: "
+				+ Arrays.asList(threads));
 	}
 
 	/**