A
Deferred object represents a reference some well-known object, that
of which may yet not be available.
A program may use a
Deferred to represent an object that is not
available/required immediately but instead available/required at some point
in the future. Alternatively a
Deferred may be used to represent an
object that is not available at the time of declaration.
Deferreds, as they are more commonly known, are neither builders or
factories. Rather each
Deferred is designed to encapsulate the
implementation to acquire a single well-known object, where as builders and
factories are typically used to construct, realize, build or allocate any
number of objects.
Deferreds may use builders and factories internally
as part of their implementation, but they themselves are not considered to be
builders or factories.
For example, a
Deferred may be used to represent a connection to a
specific server, that of which has yet to start, where as a Connection
builder/factory would instead be used to create connections to any number of
servers.
Once resolved, the referenced value of a
Deferred will not change.
While similar to Java
Futures,
Deferreds are not Java
Futures. In most circumstances,
Futures are used to represent
the result of a computation that is occurring asynchronously and thus will be
produced in the future. Calling either the
Future#get()or
Future#get(long,java.util.concurrent.TimeUnit) blocks the calling
thread, at least for some period of time, to wait for a result. More
specifically, how a thread waits for a result
Future is in fact
encapsulated by the
Future itself, with little option for a
developer to control the semantics. However calling
Deferred#get()never blocks (with exception to attempt to acquire the object), unless of
course the
Deferred implementation provides this facility
(see
Ensured as an example). ie:
Futures essentially force
calling
Threads to block,
Deferreds don't. This difference
is significant as it allows
Deferreds to present numerous types of
lazily evaluation (eg: deferred method invocation on deferred objects), that
of which is not easily possible with
Futures. Lastly
Futureprovides mechanisms to both
Future#cancel(boolean) and determine
cancellation state. This is because a
Future represents some
background operation, where as a
Deferred is simply a reference to
an object that may be available at a later point in time.
As there are many types of
Deferreds, each with their own strategies
for dealing with object acquisition, recovering from acquisition failure and
handling certainly types of objects, careful consideration should be made as
to the choice of
Deferred types to ensure that correct semantics are
achieved.
Copyright (c) 2012. All Rights Reserved. Oracle Corporation.
Oracle is a registered trademark of Oracle Corporation and/or its affiliates.