PageRenderTime 41ms CodeModel.GetById 12ms RepoModel.GetById 0ms app.codeStats 0ms

/akka-docs/java/futures.rst

https://github.com/andreum/akka
ReStructuredText | 269 lines | 187 code | 82 blank | 0 comment | 0 complexity | 3d9956f3be2a4eeacc084322fef212d8 MD5 | raw file
  1. .. _futures-java:
  2. Futures (Java)
  3. ===============
  4. .. sidebar:: Contents
  5. .. contents:: :local:
  6. Introduction
  7. ------------
  8. In Akka, a `Future <http://en.wikipedia.org/wiki/Futures_and_promises>`_ is a data structure used to retrieve the result of some concurrent operation. This operation is usually performed by an ``Actor`` or by the ``Dispatcher`` directly. This result can be accessed synchronously (blocking) or asynchronously (non-blocking).
  9. Use with Actors
  10. ---------------
  11. There are generally two ways of getting a reply from an ``UntypedActor``: the first is by a sent message (``actorRef.tell(msg);``), which only works if the original sender was an ``UntypedActor``) and the second is through a ``Future``.
  12. Using the ``ActorRef``\'s ``ask`` method to send a message will return a Future. To wait for and retrieve the actual result the simplest method is:
  13. .. code-block:: java
  14. Future[Object] future = actorRef.ask[Object](msg);
  15. Object result = future.get(); //Block until result is available, usually bad practice
  16. This will cause the current thread to block and wait for the ``UntypedActor`` to 'complete' the ``Future`` with it's reply. Due to the dynamic nature of Akka's ``UntypedActor``\s this result can be anything. The safest way to deal with this is to specify the result to an ``Object`` as is shown in the above example. You can also use the expected result type instead of ``Any``, but if an unexpected type were to be returned you will get a ``ClassCastException``. For more elegant ways to deal with this and to use the result without blocking, refer to `Functional Futures`_.
  17. Use Directly
  18. ------------
  19. A common use case within Akka is to have some computation performed concurrently without needing the extra utility of an ``UntypedActor``. If you find yourself creating a pool of ``UntypedActor``\s for the sole reason of performing a calculation in parallel, there is an easier (and faster) way:
  20. .. code-block:: java
  21. import akka.dispatch.Future;
  22. import static akka.dispatch.Futures.future;
  23. import java.util.concurrent.Callable;
  24. Future<String> f = future(new Callable<String>() {
  25. public String call() {
  26. return "Hello" + "World!";
  27. }
  28. });
  29. String result = f.get(); //Blocks until timeout, default timeout is set in akka.conf, otherwise 5 seconds
  30. In the above code the block passed to ``future`` will be executed by the default ``Dispatcher``, with the return value of the block used to complete the ``Future`` (in this case, the result would be the string: "HelloWorld"). Unlike a ``Future`` that is returned from an ``UntypedActor``, this ``Future`` is properly typed, and we also avoid the overhead of managing an ``UntypedActor``.
  31. Functional Futures
  32. ------------------
  33. A recent addition to Akka's ``Future`` is several monadic methods that are very similar to the ones used by ``Scala``'s collections. These allow you to create 'pipelines' or 'streams' that the result will travel through.
  34. Future is a Monad
  35. ^^^^^^^^^^^^^^^^^
  36. The first method for working with ``Future`` functionally is ``map``. This method takes a ``Function`` which performs some operation on the result of the ``Future``, and returning a new result. The return value of the ``map`` method is another ``Future`` that will contain the new result:
  37. .. code-block:: java
  38. import akka.dispatch.Future;
  39. import static akka.dispatch.Futures.future;
  40. import static akka.japi.Function;
  41. import java.util.concurrent.Callable;
  42. Future<String> f1 = future(new Callable<String>() {
  43. public String call() {
  44. return "Hello" + "World";
  45. }
  46. });
  47. Future<Integer> f2 = f1.map(new Function<String, Integer>() {
  48. public Integer apply(String s) {
  49. return s.length();
  50. }
  51. });
  52. Integer result = f2.get();
  53. In this example we are joining two strings together within a Future. Instead of waiting for f1 to complete, we apply our function that calculates the length of the string using the ``map`` method. Now we have a second Future, f2, that will eventually contain an ``Integer``. When our original ``Future``, f1, completes, it will also apply our function and complete the second Future with it's result. When we finally ``get`` the result, it will contain the number 10. Our original Future still contains the string "HelloWorld" and is unaffected by the ``map``.
  54. Something to note when using these methods: if the ``Future`` is still being processed when one of these methods are called, it will be the completing thread that actually does the work. If the ``Future`` is already complete though, it will be run in our current thread. For example:
  55. .. code-block:: java
  56. import akka.dispatch.Future;
  57. import static akka.dispatch.Futures.future;
  58. import static akka.japi.Function;
  59. import java.util.concurrent.Callable;
  60. Future<String> f1 = future(new Callable<String>() {
  61. public String call() {
  62. Thread.sleep(1000);
  63. return "Hello" + "World";
  64. }
  65. });
  66. Future<Integer> f2 = f1.map(new Function<String, Integer>() {
  67. public Integer apply(String s) {
  68. return s.length();
  69. }
  70. });
  71. Integer result = f2.get();
  72. The original ``Future`` will take at least 1 second to execute now, which means it is still being processed at the time we call ``map``. The function we provide gets stored within the ``Future`` and later executed automatically by the dispatcher when the result is ready.
  73. If we do the opposite:
  74. .. code-block:: java
  75. import akka.dispatch.Future;
  76. import static akka.dispatch.Futures.future;
  77. import static akka.japi.Function;
  78. import java.util.concurrent.Callable;
  79. Future<String> f1 = future(new Callable<String>() {
  80. public String call() {
  81. return "Hello" + "World";
  82. }
  83. });
  84. Thread.sleep(1000);
  85. Future<Integer> f2 = f1.map(new Function<String, Integer>() {
  86. public Integer apply(String s) {
  87. return s.length();
  88. }
  89. });
  90. Integer result = f2.get();
  91. Our little string has been processed long before our 1 second sleep has finished. Because of this, the dispatcher has moved onto other messages that need processing and can no longer calculate the length of the string for us, instead it gets calculated in the current thread just as if we weren't using a ``Future``.
  92. Normally this works quite well as it means there is very little overhead to running a quick function. If there is a possibility of the function taking a non-trivial amount of time to process it might be better to have this done concurrently, and for that we use ``flatMap``:
  93. .. code-block:: java
  94. import akka.dispatch.Future;
  95. import static akka.dispatch.Futures.future;
  96. import static akka.japi.Function;
  97. import java.util.concurrent.Callable;
  98. Future<String> f1 = future(new Callable<String>() {
  99. public String call() {
  100. return "Hello" + "World";
  101. }
  102. });
  103. Future<Integer> f2 = f1.flatMap(new Function<String, Future<Integer>>() {
  104. public Future<Integer> apply(final String s) {
  105. return future(
  106. new Callable<Integer>() {
  107. public Integer call() {
  108. return s.length();
  109. }
  110. });
  111. }
  112. });
  113. Integer result = f2.get();
  114. Now our second Future is executed concurrently as well. This technique can also be used to combine the results of several Futures into a single calculation, which will be better explained in the following sections.
  115. Composing Futures
  116. ^^^^^^^^^^^^^^^^^
  117. It is very often desirable to be able to combine different Futures with eachother, below are some examples on how that can be done in a non-blocking fashion.
  118. .. code-block:: java
  119. import akka.dispatch.Future;
  120. import static akka.dispatch.Futures.sequence;
  121. import akka.japi.Function;
  122. import java.lang.Iterable;
  123. Iterable<Future<Integer>> listOfFutureInts = ... //Some source generating a sequence of Future<Integer>:s
  124. // now we have a Future[Iterable[Int]]
  125. Future<Iterable<Integer>> futureListOfInts = sequence(listOfFutureInts);
  126. // Find the sum of the odd numbers
  127. Long totalSum = futureListOfInts.map(
  128. new Function<LinkedList<Integer>, Long>() {
  129. public Long apply(LinkedList<Integer> ints) {
  130. long sum = 0;
  131. for(Integer i : ints)
  132. sum += i;
  133. return sum;
  134. }
  135. }).get();
  136. To better explain what happened in the example, ``Future.sequence`` is taking the ``Iterable<Future<Integer>>`` and turning it into a ``Future<Iterable<Integer>>``. We can then use ``map`` to work with the ``Iterable<Integer>`` directly, and we aggregate the sum of the ``Iterable``.
  137. The ``traverse`` method is similar to ``sequence``, but it takes a sequence of ``A``s and applies a function from ``A`` to ``Future<B>`` and returns a ``Future<Iterable<B>>``, enabling parallel ``map`` over the sequence, if you use ``Futures.future`` to create the ``Future``.
  138. .. code-block:: java
  139. import akka.dispatch.Future;
  140. import static akka.dispatch.Futures.traverse;
  141. import static akka.dispatch.Futures.future;
  142. import java.lang.Iterable;
  143. import akka.japi.Function;
  144. Iterable<String> listStrings = ... //Just a sequence of Strings
  145. Future<Iterable<String>> result = traverse(listStrings, new Function<String,Future<String>>(){
  146. public Future<String> apply(final String r) {
  147. return future(new Callable<String>() {
  148. public String call() {
  149. return r.toUpperCase();
  150. }
  151. });
  152. }
  153. });
  154. result.get(); //Returns the sequence of strings as upper case
  155. It's as simple as that!
  156. Then there's a method that's called ``fold`` that takes a start-value, a sequence of ``Future``:s and a function from the type of the start-value, a timeout, and the type of the futures and returns something with the same type as the start-value, and then applies the function to all elements in the sequence of futures, non-blockingly, the execution will run on the Thread of the last completing Future in the sequence.
  157. .. code-block:: java
  158. import akka.dispatch.Future;
  159. import static akka.dispatch.Futures.fold;
  160. import java.lang.Iterable;
  161. import akka.japi.Function2;
  162. Iterable<Future<String>> futures = ... //A sequence of Futures, in this case Strings
  163. Future<String> result = fold("", 15000, futures, new Function2<String, String, String>(){ //Start value is the empty string, timeout is 15 seconds
  164. public String apply(String r, String t) {
  165. return r + t; //Just concatenate
  166. }
  167. });
  168. result.get(); // Will produce a String that says "testtesttesttest"(... and so on).
  169. That's all it takes!
  170. If the sequence passed to ``fold`` is empty, it will return the start-value, in the case above, that will be 0. In some cases you don't have a start-value and you're able to use the value of the first completing Future in the sequence as the start-value, you can use ``reduce``, it works like this:
  171. .. code-block:: java
  172. import akka.dispatch.Future;
  173. import static akka.dispatch.Futures.reduce;
  174. import java.util.Iterable;
  175. import akka.japi.Function2;
  176. Iterable<Future<String>> futures = ... //A sequence of Futures, in this case Strings
  177. Future<String> result = reduce(futures, 15000, new Function2<String, String, String>(){ //Timeout is 15 seconds
  178. public String apply(String r, String t) {
  179. return r + t; //Just concatenate
  180. }
  181. });
  182. result.get(); // Will produce a String that says "testtesttesttest"(... and so on).
  183. Same as with ``fold``, the execution will be done by the Thread that completes the last of the Futures, you can also parallize it by chunking your futures into sub-sequences and reduce them, and then reduce the reduced results again.
  184. This is just a sample of what can be done.
  185. Exceptions
  186. ----------
  187. Since the result of a ``Future`` is created concurrently to the rest of the program, exceptions must be handled differently. It doesn't matter if an ``UntypedActor`` or the dispatcher is completing the ``Future``, if an ``Exception`` is caught the ``Future`` will contain it instead of a valid result. If a ``Future`` does contain an ``Exception``, calling ``get`` will cause it to be thrown again so it can be handled properly.