public final class Promise<T> extends Object
public T findSomething(Args args);then this method should be represented in promise-oriented way like this:
public Promise<T> findSomethingPromise(Args args);
In this case, the call to findSomething(args)
is semantically equivalent to
findSomethingPromise(args).
. There may be service-specific difference between
those two forms of invocation. If await
()findSomething
throws exception, then await
will
wrap them into PromiseException
. If findSomething
consults some kind of local cache with subscription,
then it may be defined by the service to return immediately and only retrieve the result from the cache, while
findSomethingPromise
is a proper form that makes potentially time-consuming call to a back end data provider.
findSomethingPromise
via findSomething
using an Executor
for
background computation looks like this:
public Promise<T> findSomethingPromise(final Args args) { final Promise<T> promise = newA more advanced implementation may also cancel pending and/or ongoing computation when client cancels the promise or times out waiting for a promise to be completed. The sketch of such implementation using anPromise
<T>(); executor.execute
(new Runnable() { public void run() { try { T result = findSomething(args); promise.complete
(result); } catch (Throwable t) { promise.completeExceptionally
(t); } } }); return promise; }
ExecutorService
is:
public Promise<T> findSomethingPromise(final Args args) { final Promise<T> promise = newPromise
<T>(); final Future<?> future = executor.submit
(new Runnable() { public void run() { try { T result = findSomething(args); promise.complete
(result); } catch (Throwable t) { promise.completeExceptionally
(t); } } }); promise.whenDone(newPromiseHandler
() { public voidpromiseDone
(Promise<? extends T> promise) { future.cancel
(true); // true to interrupt running task } }); return promise; }
try {
findSomething(args).await
();
handleResult(result);
} catch (Throwable t) {
handleException(t);
}
Waiting with timeout is performed by replacing await
call with await(timeout, unit)
.
The same handling can be performed in the service provider thread like this:
findSomething(args).whenDone(newWhen performing time-consuming operation inPromiseHandler
() { public voidpromiseDone
(Promise<? extends T> promise) { if (promise.hasResult()) handleResult(promise.getResult()); else handleException(promise.getException()); } });
PromiseHandler.promiseDone
method,
it is advisable to dedicate a separate Executor
for it and use
whenDoneAsync(promiseHandler, executor)
method.
What \ State | Initial | Result | Exception | Cancelled |
---|---|---|---|---|
Transition method | constructor |
complete |
completeExceptionally |
cancel |
isDone |
false |
true |
true |
true |
hasResult |
false |
true |
false |
false |
hasException |
false |
false |
true |
true |
isCancelled |
false |
false |
false |
true |
getResult |
null |
result |
null |
null |
getException |
null |
null |
exception |
CancellationException |
Future
and CompletableFuture
(since Java 8). However, the methods
in this class are carefully selected to minimize the interface weight and the preference is given to methods
that do no throw checked exceptions. All the names of the methods are picked to avoid conflicts with
CompletableFuture
, so this class can be potentially redesigned to extend CompletableFuture
while maintaining backwards compatibility.Constructor and Description |
---|
Promise()
Creates promise in the initial state.
|
Modifier and Type | Method and Description |
---|---|
T |
await()
Wait for computation to complete and return its result of thrown an exception in case of exceptional completion.
|
T |
await(long timeout,
TimeUnit unit)
Wait for computation to complete or timeout and return its result of throw an exception in case of exceptional completion.
|
void |
cancel()
Cancels computation.
|
void |
complete(T result)
Completes computation normally with a specified result.
|
void |
completeExceptionally(Throwable exception)
Completes computation exceptionally with a specified exception.
|
Throwable |
getException()
Returns exceptional outcome of computation.
|
T |
getResult()
Returns result of computation.
|
boolean |
hasException()
Returns
true when computation has completed exceptionally or was cancelled. |
boolean |
hasResult()
Returns
true when computation has completed normally. |
boolean |
isCancelled()
Returns
true when computation was cancelled . |
boolean |
isDone()
|
void |
whenDone(PromiseHandler<? super T> handler)
Registers a handler to be invoked exactly once when computation
completes . |
void |
whenDoneAsync(PromiseHandler<? super T> handler,
Executor executor)
Registers a handler to be invoked asynchronously exactly once when computation
completes . |
public boolean isDone()
true
when computation has completed.public boolean hasResult()
true
when computation has completed normally.
Use getResult()
method to get the result of the computation.true
when computation has completed normally.getResult()
public boolean hasException()
true
when computation has completed exceptionally or was cancelled.
Use getException()
method to get the exceptional outcome of the computation.true
when computation has completed exceptionally or was cancelled.public boolean isCancelled()
true
when computation was cancelled
.
Use getException()
method to get the corresponding CancellationException
.true
when computation was cancelled.cancel()
,
getException()
public T getResult()
result
, then
this method returns null
.hasResult()
public Throwable getException()
exception
,
then this method returns null
. If computation has completed exceptionally or was cancelled, then
the result of this method is not null
.
If computation was cancelled
, then this method returns an
instance of CancellationException
.hasException()
public T await()
interrupted
, the computation is cancelled,
the interruption flag on the current thread is set, and CancellationException
is thrown.
This method waits forever. See await(timeout, unit)
for a timed wait.
CancellationException
- if computation was cancelled.PromiseException
- if computation has completed exceptionally.public T await(long timeout, TimeUnit unit)
interrupted
, the computation is cancelled
,
the interruption flag on the current thread is set, and CancellationException
is thrown.
If the wait times out the the computation is cancelled
and CancellationException
is thrown.CancellationException
- if computation was cancelled or timed out.PromiseException
- if computation has completed exceptionally.public void cancel()
completed
.
If cancelled, then getException
will return CancellationException
,
isDone
, isCancelled
, and hasException
will return true
,
all handlers
that were installed with whenDone
and
whenDoneAsync
methods are notified by
invoking their promiseDone
method, and
all waiters on join
method throw CancellationException
.
public void complete(T result)
completed
(normally, exceptionally, or was cancelled),
If completed, then getResult
will return the specified result,
isDone
and hasResult
will return true
,
all handlers
that were installed with whenDone
and
whenDoneAsync
methods are notified by
invoking their promiseDone
method, and
all waiters on join
method return the result.
result
- the result of computation.getResult()
public void completeExceptionally(Throwable exception)
completed
,
otherwise getException()
will return the specified exception.
If completed exceptionally, then getException
will return the specified exception,
isDone
and hasException
will return true
,
all handlers
that were installed with whenDone
and
whenDoneAsync
methods are notified by
invoking their promiseDone
method, and
all waiters on join
method throw PromiseException
wrapping this exception.
exception
- the exception.NullPointerException
- if exception is null.getException()
public void whenDone(PromiseHandler<? super T> handler)
completes
.
The handler's promiseDone
method
is invoked immediately when this computation has already completed,
otherwise it will be invoked synchronously in the future when computation
completes normally
,
or exceptionally
,
or is cancelled
from the same thread that had invoked one of the completion methods.
Exceptions that are produced by the invocation of
PromiseHandler.promiseDone
method
are caught and logged.handler
- the handler.NullPointerException
- if handler is null.public void whenDoneAsync(PromiseHandler<? super T> handler, Executor executor)
completes
.
The handler's promiseDone
method
is invoked asynchronously in the future with the given executor
when computation
completes normally
,
or exceptionally
,
or is cancelled
.handler
- the handler.executor
- the executor.NullPointerException
- if handler or executor is null.Copyright © 2014 Devexperts. All Rights Reserved.