Class ResultExchange<T>
java.lang.Object
de.aristaflow.adept2.util.threading.ResultExchange<T>
- Type Parameters:
T- The type of the result.
- All Implemented Interfaces:
Future<T>
This class provides the means to exchange a result between different threads. It resembles a
The implementation is based on a
Future except for the possibility to cancel it. The implementation is based on a
CountDownLatch. This is awaited by the result readers
and signalled by the writer.
When using it make sure to call endComputation(Object) or
failComputation(Throwable) under all circumstances after making the instance of
ResultExchange available to other threads, e. g.:
ResultExchange re;
Throwable t = new Throwable("Computation failed due to unknown reasons");
try
{
...
re.endComputation(...);
t = null;
}
catch (Exception e)
{
...
t = e;
}
finally
{
re.failComputation(t);
}
-
Field Summary
FieldsModifier and TypeFieldDescriptionprotected booleanWhether the result has been computed (or failed to compute).protected final CountDownLatchThe latch for signalling the result being available.protected TThe result after computation.protected ThrowableThe throwable which caused the computation to fail. -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionbooleancancel(boolean mayInterruptIfRunning) voidendComputation(T res) Computation has ended with the designated result to be provided by thisResultExchange.voidComputation has failed with the designated throwable to be provided by thisResultExchangeunless the designated throwable isnull.get()booleanbooleanisDone()
-
Field Details
-
latch
The latch for signalling the result being available. -
done
protected volatile boolean doneWhether the result has been computed (or failed to compute). -
result
The result after computation. -
throwable
The throwable which caused the computation to fail.
-
-
Constructor Details
-
ResultExchange
public ResultExchange()Creates a new result exchange.
-
-
Method Details
-
endComputation
Computation has ended with the designated result to be provided by thisResultExchange.- Parameters:
res- The result to be provided by thisResultExchange
-
failComputation
Computation has failed with the designated throwable to be provided by thisResultExchangeunless the designated throwable isnull. This helps signalling the computation within afinally.- Parameters:
t- The throwable to be provided instead of a result by thisResultExchange. Usenullto indicate no failure.
-
cancel
public boolean cancel(boolean mayInterruptIfRunning) -
isCancelled
public boolean isCancelled()- Specified by:
isCancelledin interfaceFuture<T>
-
isDone
public boolean isDone() -
get
- Specified by:
getin interfaceFuture<T>- Throws:
InterruptedExceptionExecutionException
-
get
public T get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException - Specified by:
getin interfaceFuture<T>- Throws:
InterruptedExceptionExecutionExceptionTimeoutException
-