Add stack-safe async loop support with trampoline pattern#1905
Open
vbabanin wants to merge 5 commits intomongodb:mainfrom
Open
Add stack-safe async loop support with trampoline pattern#1905vbabanin wants to merge 5 commits intomongodb:mainfrom
vbabanin wants to merge 5 commits intomongodb:mainfrom
Conversation
- Add AsyncTrampoline class to prevent stack overflow in loops by converting callback recursion into iterative execution - Add thenRunWhileLoop method to AsyncRunnable to support while-loop semantics where condition is checked before body execution - Integrate trampoline into AsyncCallbackLoop by making LoopingCallback implement Runnable to avoid per-iteration lambda allocation JAVA-6120
vbabanin
commented
Mar 6, 2026
|
|
||
| LoopingCallback(final SingleResultCallback<Void> callback) { | ||
| wrapped = callback; | ||
| nextIteration = () -> body.run(this); |
Member
Author
There was a problem hiding this comment.
The nextIteration is reused to avoid creation of extra objects via LambdaMetafactory as we have the capturing lambda.
bounce.work = task is a write to a heap object's field, which can be considered an automatic escape in the JIT's analysis. Even if the Bounce object is short-lived, the JIT sees "object written to another object's field" and should give up.
The AsyncCallbackLoop JMH GC profiling (OpenJDK 17.0.10 LTS, 64-bit Server VM, mixed mode with compressed oops).
| Metric | Runnable (this) | Lambda |
|---|---|---|
| Alloc rate | 0.039 MB/sec | 96.924 MB/sec |
| Alloc per op | 64 B/op | 160,048 B/op |
| GC count | ~ 0 | 10 |
| GC time | 0 ms | 9 ms |
For Lambda case:
Per iteration: 1 lambda * 16 bytes = 16 B
- Per op (10,000 iterations): 10,000 * 16 = 160,000 B
- Plus one-time objects ~ 48 B
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
JAVA-6120