RecursiveTask.java 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. /*
  2. * Written by Doug Lea with assistance from members of JCP JSR-166
  3. * Expert Group and released to the public domain, as explained at
  4. * http://creativecommons.org/publicdomain/zero/1.0/
  5. */
  6. package jsr166y;
  7. /**
  8. * A recursive result-bearing {@link ForkJoinTask}.
  9. *
  10. * <p>For a classic example, here is a task computing Fibonacci numbers:
  11. *
  12. * <pre> {@code
  13. * class Fibonacci extends RecursiveTask<Integer> {
  14. * final int n;
  15. * Fibonacci(int n) { this.n = n; }
  16. * protected Integer compute() {
  17. * if (n <= 1)
  18. * return n;
  19. * Fibonacci f1 = new Fibonacci(n - 1);
  20. * f1.fork();
  21. * Fibonacci f2 = new Fibonacci(n - 2);
  22. * return f2.compute() + f1.join();
  23. * }
  24. * }}</pre>
  25. *
  26. * However, besides being a dumb way to compute Fibonacci functions
  27. * (there is a simple fast linear algorithm that you'd use in
  28. * practice), this is likely to perform poorly because the smallest
  29. * subtasks are too small to be worthwhile splitting up. Instead, as
  30. * is the case for nearly all fork/join applications, you'd pick some
  31. * minimum granularity size (for example 10 here) for which you always
  32. * sequentially solve rather than subdividing.
  33. *
  34. * @since 1.7
  35. * @author Doug Lea
  36. */
  37. public abstract class RecursiveTask<V> extends ForkJoinTask<V> {
  38. private static final long serialVersionUID = 5232453952276485270L;
  39. /**
  40. * The result of the computation.
  41. */
  42. V result;
  43. /**
  44. * The main computation performed by this task.
  45. */
  46. protected abstract V compute();
  47. public final V getRawResult() {
  48. return result;
  49. }
  50. protected final void setRawResult(V value) {
  51. result = value;
  52. }
  53. /**
  54. * Implements execution conventions for RecursiveTask.
  55. */
  56. protected final boolean exec() {
  57. result = compute();
  58. return true;
  59. }
  60. }