Repository navigation
Java 25: Scoped Values vs ThreadLocal (JEP 506) - #100
Merged
Merged
Conversation
Test Results266 tests +4 263 ✅ +4 5s ⏱️ -1s Results for commit 836dda6. ± Comparison against base commit b209ba5. This pull request skips 1 and un-skips 1 tests. |
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.
What you'll learn
ScopedValue.where(KEY, value).run(...)/.call(...), and that it is only visible inside that callisBound()andget()reflect the binding's lifetime, throwingNoSuchElementExceptiononce it's gonewhere(...).run(...)rebinds aScopedValueonly for the nested call, restoring the outer value afterwardScopedValuehas noset()/remove(), unlike the mutable, leak-proneThreadLocalWhy it matters
ScopedValue(finalized in JDK 25 via JEP 506) gives you immutable, structured context propagation without the risk of forgetting aThreadLocal.remove()in a pooled thread, and it composes safely with virtual threads and structured concurrency.Read more
JEP 506: Scoped Values
Quiz
What does this print?
Answer
The nested
run()only rebindsUSERfor its own body; once it returns, the outer binding is restored unchanged.Note on testing: JDK 25 (required by this project's Gradle toolchain) could not be provisioned in this sandbox — the toolchain auto-download host (
api.foojay.io) and direct JDK download hosts are blocked by the environment's network policy. TheScopedValueAPI used here is unchanged from its JDK 21 preview form (just finalized, no--enable-previewneeded), so every test method's logic was independently verified by compiling and running an equivalent standalone program withjavac --release 21 --enable-preview/java --enable-preview, confirming the exact assertions in this PR. Opening as a draft; CI will run the real build on JDK 25.Closes #87