Class Async

java.lang.Object
org.kiwiproject.concurrent.Async

public final class Async extends Object
Static utilities that work with CompletableFuture and can make testing easier by permitting selective (e.g., in unit tests) forcing of synchronous behavior for things that would normally execute asynchronously. This applies only to some methods, so read the method's documentation before assuming.

Use the xxxAsync methods when you need to control concurrent behavior and make things deterministic during unit tests (e.g., blocking on futures). Note this does actually change the true behavior of the code under test, since methods will execute synchronously, so use them with care, caution, and understanding.

In tests, you can call the setUnitTestAsyncMode(Mode) method with Async.Mode.DISABLED to force synchronous behavior when calling Async methods. This may be desirable in certain situations to make testing asynchronous code easier. Note that this is a global change, such that all calls to Async methods will then behave as synchronous calls and block until the operation is complete. So, when using this capability in tests, you need to be careful to reset the behavior after tests complete. This may also cause problems if tests are executed in parallel, and some tests use this feature, but some do not.

The kiwi-test library provides a JUnit extension, AsyncModeDisablingExtension, that disables asynchronous behavior in Async before each test, then re-enables it after each test.

Alternatively, you can use AsyncHelper, which will let you control asynchronous behavior in each instance or to use a mock instance in tests. Either of these avoids problems with multiple threads or running tests in parallel.

See Also:
Implementation Note:
the "asyncMode" flag is a STATIC variable and should only ever be changed during testing using the setUnitTestAsyncMode(Mode) method. Generally, you should set this before tests and reset after they have run. Note also this almost certainly will cause unexpected behavior if tests are run in parallel.