Constructor. @param deferreds All the Deferreds we want to group. @param ordered If true, the results will be presented in the same order as the Deferreds are in the deferreds argument. If false, results will be presented in the order in which they arrive. In other words, ass
(final Collection<Deferred<T>> deferreds,
final boolean ordered)
| 67 | * is determined by the order in which callbacks fire on A, B, and C. |
| 68 | */ |
| 69 | public DeferredGroup(final Collection<Deferred<T>> deferreds, |
| 70 | final boolean ordered) { |
| 71 | nresults = deferreds.size(); |
| 72 | results = new ArrayList<Object>(nresults); |
| 73 | |
| 74 | if (nresults == 0) { |
| 75 | parent.callback(results); |
| 76 | return; |
| 77 | } |
| 78 | |
| 79 | // Callback used to collect results in the order in which they appear. |
| 80 | final class Notify<T> implements Callback<T, T> { |
| 81 | public T call(final T arg) { |
| 82 | recordCompletion(arg); |
| 83 | return arg; |
| 84 | } |
| 85 | public String toString() { |
| 86 | return "notify DeferredGroup@" + DeferredGroup.super.hashCode(); |
| 87 | } |
| 88 | }; |
| 89 | |
| 90 | // Callback that preserves the original orders of the Deferreds. |
| 91 | final class NotifyOrdered<T> implements Callback<T, T> { |
| 92 | private final int index; |
| 93 | NotifyOrdered(int index) { |
| 94 | this.index = index; |
| 95 | } |
| 96 | public T call(final T arg) { |
| 97 | recordCompletion(arg, index); |
| 98 | return arg; |
| 99 | } |
| 100 | public String toString() { |
| 101 | return "notify #" + index + " DeferredGroup@" |
| 102 | + DeferredGroup.super.hashCode(); |
| 103 | } |
| 104 | }; |
| 105 | |
| 106 | if (ordered) { |
| 107 | int i = 0; |
| 108 | for (final Deferred<T> d : deferreds) { |
| 109 | results.add(null); // ensures results.set(i, result) is valid. |
| 110 | // Note: it's important to add the callback after the line above, |
| 111 | // as the callback can fire at any time once it's been added, and |
| 112 | // if it fires before results.set(i, result) is valid, we'll get |
| 113 | // an IndexOutOfBoundsException. |
| 114 | d.addBoth(new NotifyOrdered<T>(i++)); |
| 115 | } |
| 116 | } else { |
| 117 | final Notify<T> notify = new Notify<T>(); |
| 118 | for (final Deferred<T> d : deferreds) { |
| 119 | d.addBoth(notify); |
| 120 | } |
| 121 | } |
| 122 | } |
| 123 | |
| 124 | /** |
| 125 | * Returns the parent {@link Deferred} of the group. |