ScopedValue: Capturing current bindings

Attila Kelemen attila.kelemen85 at gmail.com
Wed May 31 19:38:32 UTC 2023


The gain would be that I can use the upper bindings without worrying
that there are new bindings. For my DI framework example, the problem
is that a DI framework might want to bind a factory (maybe because it
is a lazy singleton, or not a singleton at all), which is then queried
ina nested scope. However, if we do not capture the current
ScopedValue bindings at the time the DI framework captures its own
factories, then the factories might behave differently depending on
the context they were called for, and this would be unacceptable for a
DI framework (you want very predictable behaviour for your factories).

Andrew Haley <aph-open at littlepinkcloud.com> ezt írta (időpont: 2023.
máj. 31., Sze, 11:26):
>
> It may be that I am misunderstanding you, but:
>
> On 5/30/23 17:58, Attila Kelemen wrote:
>
>  > 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.
>
> If we're still within the scope, then surely we don't need to capture
> the bindings. If we're within the scope, the values will still be
> bound.
>
>  > 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.
>
> But what would be the point, even if we could do this? All we'd be
> doing would be making sure that nesting was done correctly with a
> run-time check, rather than simply enforcing that by construction.
>
> We want to be able to do this in Class X:
>
>    private static final ScopedValue<Object> RESOURCE = ScopedValue.newInstance();
>
>    ...
>      ScopedValue.where(RESOURCE, null).run(action);
>
> in the knowledge that RESOURCE.get() will always be null within
> action's dynamic scope, unless some code in Class X changes it.
> If action has a way to restore previously captured scoped values,
> we can't guarantee that.
>
> --
> 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