ScopedValue: Capturing current bindings

Andrew Haley aph-open at littlepinkcloud.com
Mon Jun 5 16:52:34 UTC 2023


On 6/2/23 18:54, Attila Kelemen wrote:
   >
   >     OK, so it's possible for application code called from a framework to
   >     override the caller's context, as long as that context was a parent
   >     of the current context. That seems like a significant weakening of
   >     the guarantees that scoped values provide.
   >
   >

   > Yes, and a few days ago I would have also said that it might weaken
   > the guarantees. However, you might have missed it in the infinite
   > sea of emails, but I have actually figured out a way how this can be
   > implemented [1].

But it doesn't do the same thing. It runs the code in another thread,
so per-thread guarantees are maintained. I'm fine with that. It's
always possible to hand a task from Thread A to Thread B, as long as
both threads co-operate.

   > The only problem is that the implementation is very inefficient
   > compared to the fact that it effectively just does what you wrote:
   > "override the caller's context, as long as that context was a parent
   > of the current context" (does it with an otherwise completely
   > pointless parallelization). See `CapturedScopes.withCurrentContext`
   > (I called this method `withCapturedContext` in a previous email,
   > sorry for the inconsistency).
   >
   > That is, providing this feature in the JDK would not weaken any
   > guarantees.

We need the ability to revoke access.

Consider this scenario. You have a resource that is entirely
unsychronized, so must be accessed by only one thread at a time. A
thread-locked scoped value (called CAP) is used as a capability to
access the region. CAP is a handle which contains a reference to
the owning thread and a reference to the memory region.

Thread B needs access, so it requests CAP from the current owner,
Thread A. Thread A creates a new capability locked to Thread B, hands
it over, then continues executing, with its own CAP bound either
to null or to the new capability.

If some code now running in A had stashed a previous set of scoped
value bindings and could restore them, two threads A and B could now
appear to own the same memory region.

-- 
Andrew Haley  (he/him)
Java Platform Lead Engineer
Red Hat UK Ltd. <https://www.redhat.com>
https://keybase.io/andrewhaley
EAC8 43EB D3EF DB98 CC77 2FAD A5CD 6035 332F A671


More information about the loom-dev mailing list