UP | HOME
2015-10-05 | ../../

Java Futures and Callables

1 Futures

1.1 Unwaited Computations

  1. 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.
  2. 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.
  3. Futures are also called promises. Many languages, e.g., Scala, have had futures. Also called, asynchronous computation.

1.2 Java8 Futures

  1. java.util.concurrent.Future<V> interface
  2. 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.
  3. Off you go do other computations.
  4. 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.
  5. Your code does not block/wait. Off you go do computations below this line.
  6. When you must have the result, of this future work you created, do String rs = fto.get();
  7. Control will not go past the above line until startWork delivers a result, that we obtain via the get() method.
  8. A future task class implements Runnable, and so executable by an Executor.

2 Callables

  1. java.util.concurrent.Callable<V> interface
  2. Similar to Runnable, but returns a result of type V.
  3. Example: ../Java/src/CallableEx.java Executor with Future ../Java/src/CallableEx.java.html

Copyright © 2015 www.wright.edu/~pmateti