in junit-jupiter-api/src/main/java/org/junit/jupiter/api/AssertTimeout.java [128:174]
private static <T> T assertTimeoutPreemptively(Duration timeout, ThrowingSupplier<T> supplier,
Object messageOrSupplier) {
AtomicReference<Thread> threadReference = new AtomicReference<>();
ExecutorService executorService = Executors.newSingleThreadExecutor(new TimeoutThreadFactory());
try {
Future<T> future = executorService.submit(() -> {
try {
threadReference.set(Thread.currentThread());
return supplier.get();
}
catch (Throwable throwable) {
throw ExceptionUtils.throwAsUncheckedException(throwable);
}
});
long timeoutInMillis = timeout.toMillis();
try {
return future.get(timeoutInMillis, TimeUnit.MILLISECONDS);
}
catch (TimeoutException ex) {
String message = buildPrefix(nullSafeGet(messageOrSupplier)) + "execution timed out after "
+ timeoutInMillis + " ms";
Thread thread = threadReference.get();
if (thread != null) {
ExecutionTimeoutException exception = new ExecutionTimeoutException(
"Execution timed out in thread " + thread.getName());
exception.setStackTrace(thread.getStackTrace());
throw new AssertionFailedError(message, exception);
}
else {
throw new AssertionFailedError(message);
}
}
catch (ExecutionException ex) {
throw ExceptionUtils.throwAsUncheckedException(ex.getCause());
}
catch (Throwable ex) {
throw ExceptionUtils.throwAsUncheckedException(ex);
}
}
finally {
executorService.shutdownNow();
}
}