ScopedValue: Capturing current bindings

Attila Kelemen attila.kelemen85 at gmail.com
Tue May 30 16:58:18 UTC 2023


But then `CapturedScopedValueContext.inContext` would be created by
the JDK, and it could verify that we are still within the scope, which
would ensure that resources (like the one you have mentioned) passed
in a scoped value are not used outside of the scope. I don't see that
it would be fundamentally different compared to the check of
`StructuredTaskScope.fork`, which you can also try to use outside of
the scope in which case it would just throw an exception. Similarly,
`CapturedScopedValueContext.inContext` would behave similarly as
`StructuredTaskScope.fork`. The only relaxation would be that
`CapturedScopedValueContext.inContext` would be allowed to be called
in a nested context (while `fork` is not, because that would be
misleading). Granted, this check can't be made as efficient as `fork`,
but I would assume that in reasonable circumstances, the efficiency
would be satisfactory.

Andrew Haley <aph-open at littlepinkcloud.com> ezt írta (időpont: 2023.
máj. 30., K, 11:14):
>
> On 5/23/23 15:07, Attila Kelemen wrote:
> > What I wish for is a way to capture the current scoped values, and
> > later execute code with the captured scoped values.
>
> Thanks for the thought. An earlier version of scoped values did permit
> this to be done, but it was removed.
>
> That's because, for reasons of integrity, we need to be able to guarantee
> that, when a binding scope terminates, the value is no longer bound in
> any thread. And that it will never be re-bound without an explicit binding
> operation.
>
> The scope used by a scoped value binding is the current scope, at runtime.
> This is by design. The only way to capture a scope and use it in a different
> context is by a thread, in a structured concurrency context.
>
> Because of this rule we can safely do things like
>
>     MemType memoryRegion = allocateMem()
>     try {
>       ScopedValue.where(REGION, memoryRegion).run(someActions);
>     } finally {
>       memoryRegion.close();
>     }
>
> ... in the secure knowledge that no one will ever see REGION.get() return a
> value after the region has been closed.
>
> This is correctness by construction: rather than detecting some errors
> at runtime, we make them impossible.
>
> --
> 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