|
17 | 17 |
|
18 | 18 | import com.mongodb.annotations.NotThreadSafe; |
19 | 19 | import com.mongodb.internal.async.SingleResultCallback; |
20 | | -import com.mongodb.internal.async.function.CallbackChain.Element; |
21 | 20 | import com.mongodb.lang.Nullable; |
22 | 21 |
|
23 | 22 | import java.util.function.Supplier; |
@@ -63,21 +62,35 @@ public void run(final SingleResultCallback<Void> callback) { |
63 | 62 |
|
64 | 63 | private static final class Body { |
65 | 64 | private final AsyncCallbackRunnable wrapped; |
66 | | - @Nullable |
67 | | - private final CallbackChain chain; |
| 65 | + private final boolean optimized; |
| 66 | + private boolean executingChain; |
68 | 67 |
|
69 | 68 | private Body(final boolean optimized, final AsyncCallbackRunnable body) { |
70 | 69 | this.wrapped = body; |
71 | | - this.chain = optimized ? new CallbackChain() : null; |
| 70 | + this.optimized = optimized; |
| 71 | + executingChain = false; |
72 | 72 | } |
73 | 73 |
|
74 | 74 | @Nullable |
75 | 75 | Element run(final LoopingCallback loopingCallback) { |
76 | 76 | Element[] mutableElement = new Element[1]; |
77 | 77 | wrapped.run((r, t) -> { |
78 | | - Element nextCallbackToComplete = loopingCallback.onResult(r, t); |
79 | | - if (!CallbackChain.execute(chain, nextCallbackToComplete)) { |
80 | | - mutableElement[0] = nextCallbackToComplete; |
| 78 | + Element element = loopingCallback.onResult(r, t); |
| 79 | + if (!optimized && element != null) { |
| 80 | + element.execute(); |
| 81 | + return; |
| 82 | + } |
| 83 | + if (element == null || executingChain) { |
| 84 | + mutableElement[0] = element; |
| 85 | + } else { |
| 86 | + executingChain = true; |
| 87 | + try { |
| 88 | + do { |
| 89 | + element = element.execute(); |
| 90 | + } while (element != null); |
| 91 | + } finally { |
| 92 | + executingChain = false; |
| 93 | + } |
81 | 94 | } |
82 | 95 | }); |
83 | 96 | return mutableElement[0]; |
@@ -117,4 +130,9 @@ public Element onResult(@Nullable final Void result, @Nullable final Throwable t |
117 | 130 | } |
118 | 131 | } |
119 | 132 | } |
| 133 | + |
| 134 | + interface Element { |
| 135 | + @Nullable |
| 136 | + Element execute(); |
| 137 | + } |
120 | 138 | } |
0 commit comments