Class WaitForAsyncUtils
- java.lang.Object
-
- org.testfx.util.WaitForAsyncUtils
-
public final class WaitForAsyncUtils extends java.lang.ObjectProvides static methods for handling execution on different threads. The "Test Thread" is usually running on the main thread, while the GUI runs on the "FX Application Thread". Additionally, tasks may also be started on different asynchronous threads.General Convention (Method Names)
asyncmethods without a suffix refer to some unknown thread in a thread pool.- Methods ending with the suffix
Fxrefer to the "FX application thread".
Exception Handling
As exceptions on different threads are thrown the caller is usually not aware of these exceptions. Exceptions returned directly from this framework are wrapped in
RuntimeExceptions.There are two ways this class notifies the user of exceptions:
- The returned
Future. - The internal exception stack.
Usually exceptions are forwarded to the
Futurereturned by the methods of this class. When the calling thread callsFuture.get()on theFutureany exceptions encountered during execution will be thrown. AllwaitFormethods acquire the value of theFutureand accordingly throw the same exceptions.The internal exception stack stores all unhandled exceptions thrown during direct calls to the
asyncmethods. As this class can not guarantee that exceptions in these methods are handled properly, it will internally store these exceptions. The exceptions will be in the stack, until they are handled somewhere in the application. If the fieldautoCheckExceptionis set to true, any subsequent calls to one of theasyncmethods will throw one of those exceptions.
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description private static classWaitForAsyncUtils.ASyncFXCallable<X>Internally usedCallablethat handles all the async stuff.private static classWaitForAsyncUtils.DefaultThreadFactory
-
Field Summary
Fields Modifier and Type Field Description static booleanautoCheckExceptionIf true any call to anasyncmethod will check for the occurrence of unhandled exceptions.static booleancheckAllExceptionsIf true any call to anasyncmethod will check for the occurrence of unhandled exceptions in anyThread.private static longCONDITION_SLEEP_IN_MILLISprivate static java.util.Queue<java.lang.Throwable>EXCEPTIONSprivate static java.util.concurrent.ExecutorServiceEXECUTOR_SERVICEprivate static java.lang.StringPAINT_COLLECTORstatic booleanprintExceptionIf true any exceptions encountered during execution of theasyncmethods will be printed to stderr.private static intSEMAPHORE_LOOPS_COUNTprivate static longSEMAPHORE_SLEEP_IN_MILLISprivate static booleanTRACE_FETCHIf true exceptions will be printed when they are fetched by a caller.
-
Constructor Summary
Constructors Constructor Description WaitForAsyncUtils()
-
Method Summary
All Methods Static Methods Concrete Methods Modifier and Type Method Description static java.util.concurrent.Future<java.lang.Void>async(java.lang.Runnable runnable)Runs the givenRunnableon a newThreadand returns aFuturethat is set on finish or error.static java.util.concurrent.Future<java.lang.Void>async(java.lang.Runnable runnable, boolean throwExceptions)Runs the givenRunnableon a newThreadand returns aFuturethat is set on finish or error.static <T> java.util.concurrent.Future<T>async(java.util.concurrent.Callable<T> callable)Calls the givenCallableon a newThreadand returns aFuturethat is set on finish or error.static <T> java.util.concurrent.Future<T>async(java.util.concurrent.Callable<T> callable, boolean throwExceptions)Calls the givenCallableon a newThreadand returns aFuturethat is set on finish or error.static java.util.concurrent.Future<java.lang.Void>asyncFx(java.lang.Runnable runnable)Runs the givenRunnableon the JavaFX Application Thread at some unspecified time in the future and returns aFuturethat is set on finish or error.static <T> java.util.concurrent.Future<T>asyncFx(java.util.concurrent.Callable<T> callable)Calls the givenCallableon the JavaFX Application Thread at some unspecified time in the future and returns aFuturethat is set on finish or error.private static voidblockFxThreadWithSemaphore()private static booleancallConditionAndReturnResult(java.util.concurrent.Callable<java.lang.Boolean> condition)static voidcheckException()Checks if an exception in an async task occurred that has not been checked currently.private static voidcheckExceptionWrapped()Internal function that throws Exceptions.private static java.time.temporal.ChronoUnitchronoUnit(java.util.concurrent.TimeUnit unit)static voidclearExceptions()Clears all unhandled exceptions.private static java.lang.ThrowablegetCheckException()Pops an exception from the stack and adds an entry in the stack trace to notify the user that this is not the original place of the exception.private static voidprintException(java.lang.Throwable e, java.lang.StackTraceElement[] trace)private static java.lang.StringprintTrace(java.lang.StackTraceElement[] st)Returns aStringcontaining the printed stacktrace.private static voidregisterException(java.lang.Throwable throwable)Used to add an exception on the stack.private static voidrunOnFxThread(java.lang.Runnable runnable)private static voidsetup()Needs to be called to setup WaitForAsyncUtils before the first use.static voidsleep(long duration, java.util.concurrent.TimeUnit timeUnit)Sleeps the current thread for the given duration.static voidwaitFor(long timeout, java.util.concurrent.TimeUnit timeUnit, java.util.concurrent.Callable<java.lang.Boolean> condition)Waits for givenCallableto return true otherwise times out with aTimeoutException.static <T> TwaitFor(long timeout, java.util.concurrent.TimeUnit timeUnit, java.util.concurrent.Future<T> future)Waits for givenFutureto be set and returnsT, otherwise times out with aTimeoutException.static voidwaitFor(long timeout, java.util.concurrent.TimeUnit timeUnit, javafx.beans.value.ObservableBooleanValue booleanValue)Waits for givenObservableBooleanValueto return true otherwise times out with aTimeoutException.static <T> TwaitFor(java.util.concurrent.Future<T> future)Waits for the givenFutureto be set and then returns the future result of typeT.static voidwaitForAsync(long millis, java.lang.Runnable runnable)Runs the givenRunnableon a newThreadand waitsmillismilliseconds for it to finish, otherwise times out with aTimeoutException.static <T> TwaitForAsync(long millis, java.util.concurrent.Callable<T> callable)Calls the givenCallableon a newThreadand waitsmillismilliseconds for it to finish.static voidwaitForAsyncFx(long millis, java.lang.Runnable runnable)Runs the givenRunnableon the JavaFX Application Thread at some unspecified time in the future and waitsmillismilliseconds for it to finish, otherwise times out with aTimeoutException.static <T> TwaitForAsyncFx(long millis, java.util.concurrent.Callable<T> callable)Calls the givenCallableon the JavaFX Application Thread at some unspecified time in the future and waitsmillismilliseconds for it to finish.static voidwaitForFxEvents()Waits for the event queue of the "JavaFX Application Thread" to be completed, as well as any new events triggered in it.static voidwaitForFxEvents(int attemptsCount)Waits up toattemptsCountattempts for the event queue of the "JavaFX Application Thread" to be completed, as well as any new events triggered on it.private static <T> TwaitForMillis(long millis, java.util.concurrent.Future<T> future)
-
-
-
Field Detail
-
CONDITION_SLEEP_IN_MILLIS
private static final long CONDITION_SLEEP_IN_MILLIS
- See Also:
- Constant Field Values
-
SEMAPHORE_SLEEP_IN_MILLIS
private static final long SEMAPHORE_SLEEP_IN_MILLIS
- See Also:
- Constant Field Values
-
SEMAPHORE_LOOPS_COUNT
private static final int SEMAPHORE_LOOPS_COUNT
- See Also:
- Constant Field Values
-
PAINT_COLLECTOR
private static final java.lang.String PAINT_COLLECTOR
- See Also:
- Constant Field Values
-
EXECUTOR_SERVICE
private static final java.util.concurrent.ExecutorService EXECUTOR_SERVICE
-
EXCEPTIONS
private static final java.util.Queue<java.lang.Throwable> EXCEPTIONS
-
printException
public static boolean printException
If true any exceptions encountered during execution of theasyncmethods will be printed to stderr. The exceptions will be printed at the time they occur (not when fetched).
-
autoCheckException
public static boolean autoCheckException
If true any call to anasyncmethod will check for the occurrence of unhandled exceptions.
-
checkAllExceptions
public static boolean checkAllExceptions
If true any call to anasyncmethod will check for the occurrence of unhandled exceptions in anyThread.
-
TRACE_FETCH
private static final boolean TRACE_FETCH
If true exceptions will be printed when they are fetched by a caller. Even when they are handled properly. This field is mainly for development debug purposes.- See Also:
- Constant Field Values
-
-
Method Detail
-
setup
private static void setup()
Needs to be called to setup WaitForAsyncUtils before the first use. Currently it installs/removes the handler for uncaught exceptions depending on the flagcheckAllExceptions.
-
async
public static java.util.concurrent.Future<java.lang.Void> async(java.lang.Runnable runnable)
Runs the givenRunnableon a newThreadand returns aFuturethat is set on finish or error.You need to evaluate the returned
Futurevia (Future.get()) for exceptions or call thecheckException()method to handle exceptions after the task has finished.- Parameters:
runnable- theRunnableto run- Returns:
- the
Futureresult of theRunnable
-
async
public static java.util.concurrent.Future<java.lang.Void> async(java.lang.Runnable runnable, boolean throwExceptions)Runs the givenRunnableon a newThreadand returns aFuturethat is set on finish or error.You need to evaluate the returned
Futurevia (Future.get()) for exceptions or call thecheckException()method to handle exceptions after the task has finished.- Parameters:
runnable- theRunnableto runthrowExceptions- whether or not to throw exceptions on the executing thread- Returns:
- the
Futureresult of the runnable
-
async
public static <T> java.util.concurrent.Future<T> async(java.util.concurrent.Callable<T> callable)
Calls the givenCallableon a newThreadand returns aFuturethat is set on finish or error.You need to evaluate the returned
Futurevia (Future.get()) for exceptions or call thecheckException()method to handle exceptions after the task has finished.- Type Parameters:
T- the return type of theCallable- Parameters:
callable- theCallableto run- Returns:
- the
Futureresult of theCallable
-
async
public static <T> java.util.concurrent.Future<T> async(java.util.concurrent.Callable<T> callable, boolean throwExceptions)Calls the givenCallableon a newThreadand returns aFuturethat is set on finish or error.You need to evaluate the returned
Futurevia (Future.get()) for exceptions or call thecheckException()method to handle exceptions after the task has finished.- Type Parameters:
T- the return type of theCallable- Parameters:
callable- theCallableto runthrowExceptions- whether or not to throw exceptions on the executing thread- Returns:
- the
Futureresult of theCallable
-
asyncFx
public static java.util.concurrent.Future<java.lang.Void> asyncFx(java.lang.Runnable runnable)
Runs the givenRunnableon the JavaFX Application Thread at some unspecified time in the future and returns aFuturethat is set on finish or error.You need to evaluate the returned
Futurevia (Future.get()) for exceptions or call thecheckException()method to handle exceptions after the task has finished.- Parameters:
runnable- theRunnableto run- Returns:
- the
Futureresult of theRunnable
-
asyncFx
public static <T> java.util.concurrent.Future<T> asyncFx(java.util.concurrent.Callable<T> callable)
Calls the givenCallableon the JavaFX Application Thread at some unspecified time in the future and returns aFuturethat is set on finish or error.You need to evaluate the returned
Futurevia (Future.get()) for exceptions or call thecheckException()method to handle exceptions after the task has finished.- Type Parameters:
T- theCallabletype- Parameters:
callable- theCallable- Returns:
- the
Futureresult of theCallable
-
waitFor
public static <T> T waitFor(java.util.concurrent.Future<T> future)
Waits for the givenFutureto be set and then returns the future result of typeT.- Type Parameters:
T- the type of theFuture- Parameters:
future- theFutureto wait for to be set- Returns:
- the result of the
Future
-
waitFor
public static <T> T waitFor(long timeout, java.util.concurrent.TimeUnit timeUnit, java.util.concurrent.Future<T> future) throws java.util.concurrent.TimeoutExceptionWaits for givenFutureto be set and returnsT, otherwise times out with aTimeoutException.- Type Parameters:
T- the type of theFuture- Parameters:
timeout- the timeout to wait fortimeUnit- the time unittimeoutis infuture- theFutureto wait for to be set- Returns:
- the result of the
Future - Throws:
java.util.concurrent.TimeoutException- if the wait timed out
-
waitFor
public static void waitFor(long timeout, java.util.concurrent.TimeUnit timeUnit, java.util.concurrent.Callable<java.lang.Boolean> condition) throws java.util.concurrent.TimeoutExceptionWaits for givenCallableto return true otherwise times out with aTimeoutException. The condition will be evaluated at least once. This method will wait for the last condition to finish after a timeout.- Parameters:
timeout- the timeout to wait fortimeUnit- the time unittimeoutis incondition- the condition to wait for to be true- Throws:
java.util.concurrent.TimeoutException- if the wait timed out
-
waitFor
public static void waitFor(long timeout, java.util.concurrent.TimeUnit timeUnit, javafx.beans.value.ObservableBooleanValue booleanValue) throws java.util.concurrent.TimeoutExceptionWaits for givenObservableBooleanValueto return true otherwise times out with aTimeoutException.- Parameters:
timeout- the timeout to wait fortimeUnit- the time unittimeoutis inbooleanValue- the observable- Throws:
java.util.concurrent.TimeoutException- if the wait timed out
-
waitForFxEvents
public static void waitForFxEvents()
Waits for the event queue of the "JavaFX Application Thread" to be completed, as well as any new events triggered in it.
-
waitForFxEvents
public static void waitForFxEvents(int attemptsCount)
Waits up toattemptsCountattempts for the event queue of the "JavaFX Application Thread" to be completed, as well as any new events triggered on it.- Parameters:
attemptsCount- the number of attempts to try
-
sleep
public static void sleep(long duration, java.util.concurrent.TimeUnit timeUnit)Sleeps the current thread for the given duration.- Parameters:
duration- the duration to sleeptimeUnit- the time unitdurationis in
-
waitForAsync
public static void waitForAsync(long millis, java.lang.Runnable runnable)Runs the givenRunnableon a newThreadand waitsmillismilliseconds for it to finish, otherwise times out with aTimeoutException.- Parameters:
millis- number of milliseconds to waitrunnable- theRunnableto run
-
waitForAsync
public static <T> T waitForAsync(long millis, java.util.concurrent.Callable<T> callable)Calls the givenCallableon a newThreadand waitsmillismilliseconds for it to finish. If finished, returns the future result of typeT, otherwise times out with aTimeoutException.- Type Parameters:
T- the type returned by theCallable- Parameters:
millis- number of milliseconds to waitcallable- theCallableto call- Returns:
- the result returned by the
Callable
-
waitForAsyncFx
public static void waitForAsyncFx(long millis, java.lang.Runnable runnable)Runs the givenRunnableon the JavaFX Application Thread at some unspecified time in the future and waitsmillismilliseconds for it to finish, otherwise times out with aTimeoutException.- Parameters:
millis- number of milliseconds to waitrunnable- theRunnableto run
-
waitForAsyncFx
public static <T> T waitForAsyncFx(long millis, java.util.concurrent.Callable<T> callable)Calls the givenCallableon the JavaFX Application Thread at some unspecified time in the future and waitsmillismilliseconds for it to finish. If finished, returnsTotherwise times out with aTimeoutException.- Type Parameters:
T- the type returned by theCallable- Parameters:
millis- number of milliseconds to waitcallable- theCallableto call- Returns:
- the result returned by the
Callable
-
checkException
public static void checkException() throws java.lang.ThrowableChecks if an exception in an async task occurred that has not been checked currently. If so, the first exception will be removed and thrown by this method.- Throws:
java.lang.Throwable- if an exception has occurred in an async task
-
clearExceptions
public static void clearExceptions()
Clears all unhandled exceptions.
-
registerException
private static void registerException(java.lang.Throwable throwable)
Used to add an exception on the stack. Used by the global exception handler.- Parameters:
throwable- the throwable to add on the local exception buffer.
-
checkExceptionWrapped
private static void checkExceptionWrapped()
Internal function that throws Exceptions. It does not require handling of the Exceptions.
-
getCheckException
private static java.lang.Throwable getCheckException()
Pops an exception from the stack and adds an entry in the stack trace to notify the user that this is not the original place of the exception.- Returns:
- the exception or null if none in stack
-
waitForMillis
private static <T> T waitForMillis(long millis, java.util.concurrent.Future<T> future)
-
runOnFxThread
private static void runOnFxThread(java.lang.Runnable runnable)
-
callConditionAndReturnResult
private static boolean callConditionAndReturnResult(java.util.concurrent.Callable<java.lang.Boolean> condition)
-
blockFxThreadWithSemaphore
private static void blockFxThreadWithSemaphore()
-
printException
private static void printException(java.lang.Throwable e, java.lang.StackTraceElement[] trace)
-
printTrace
private static java.lang.String printTrace(java.lang.StackTraceElement[] st)
Returns aStringcontaining the printed stacktrace.- Parameters:
st- the stacktrace- Returns:
- a
Stringcontaining the printed stacktrace
-
chronoUnit
private static java.time.temporal.ChronoUnit chronoUnit(java.util.concurrent.TimeUnit unit)
-
-