Java Futures and Callables
1 Futures
1.1 Unwaited Computations
- Recall that when you define a method, occupying certain number of
lines in a file, it is not executed until it is invoked. Invoking
is also tied down to using the b.m() notation.
- A future computation is a delineated segment of code in some
method, that you intend to get results from some time in the
future, and the code should have access to variables in the current
scope, but with the values the variables will have at the time of
invocation.
- Futures are also called promises. Many languages, e.g., Scala,
have had futures. Also called, asynchronous computation.
1.2 Java8 Futures
java.util.concurrent.Future<V>
interface
Future<String> startWork(F) {S}
F is a list of formals, S is a
segment of code that will return a String. This defines the
future-method that you named startWork
.
- Off you go do other computations.
Future<String> fto = startWork(A);
Actual args A. This requests
the JVM to start executing the code body of startWork
; JVM may
look for an oppurtune moment to begin executing. You now have the
handle saved in fto
.
- Your code does not block/wait. Off you go do computations below
this line.
- When you must have the result, of this future work you created, do
String rs = fto.get();
- Control will not go past the above line until startWork delivers a
result, that we obtain via the
get()
method.
- A future task class implements
Runnable
, and so executable by an
Executor
.