Skip to content

BlockingPromise

Richard Hightower edited this page Apr 24, 2016 · 2 revisions

A BlockingPromise is very much like a Java Future. It is blocking. This is useful for unit testing and for legacy integration.

Promises returns a blocking promise as follows:

Blocking Promise

    /**
     * Create a blocking promise.
     * NOTE BLOCKING PROMISES ARE FOR LEGACY INTEGRATION AND TESTING ONLY!!!
     * After you create a promise you register its then and catchError and then you use it to
     * handle a callback.
     *
     * @param <T> type of result
     * @return new promise
     */
    static <T> Promise<T> blockingPromise() {
        return new BlockingPromise<>();
    }

Here are some example testing with a blocking promise from our unit tests.

Testing for a failure

    @Test
    public void testAsyncServiceWithInvokePromiseFail() {


        Promise<URI> promise = Promises.blockingPromise();
 
        /* Set up handlers. */
        promise.then(this::handleSuccess)
                .catchError(this::handleError);

        /* Force a failure by passing null. */
        asyncServiceDiscovery.lookupService(promise, null);


        try {
            promise.get();
            fail();
        } catch (Exception ex) {

        }
...
    }

Here is another example that uses a blocking promise to do a unit test (success path).

Using blocking promise (success)

    @Test
    public void testAsyncWithBlockingPromise() throws Exception {

        TestService testService = new TestService();
        Employee[] employee = new Employee[1];
        Expected[] value = new Expected[1];

        /* Note this is only for legacy integration and testing. */
        Promise<Employee> promise = Promises.blockingPromise();

        promise.then(e -> employee[0] = e);
        promise.thenExpect(employeeValue -> value[0] = employeeValue);


        testService.async(promise);

        assertNotNull(promise.get());
        assertNotNull(promise.expect());
        assertTrue(promise.complete());
        assertFalse(promise.failure());
        assertTrue(promise.success());
        assertNull(promise.cause());
        assertNotNull(employee[0]);

        assertNotNull(value[0]);

    }

You can even use blocking promises with services that return a promise, i.e., an invokable promise.

Test Invokable Promise Example with a blocking promise

    @Test
    public void testAsyncServiceWithInvokePromiseFail() {


        Promise<URI> promise = Promises.blockingPromise();
        promise.then(this::handleSuccess)
                .catchError(this::handleError);

        asyncServiceDiscovery.lookupService(null).invokeWithPromise(promise);


        try {
            promise.get();
            fail();
        } catch (Exception ex) {

        }
...
    }

Blocking promises are very important for legacy integration, prototyping and unit testing, but you should not use them in a true reactive Java app.

You can’t perform that action at this time.