ScopedValue: Capturing current bindings

Attila Kelemen attila.kelemen85 at gmail.com
Fri Jun 2 18:13:20 UTC 2023


Robert Engels <rengels at ix.netcom.com> ezt írta (időpont: 2023. jún. 2., P,
12:26):

> I think what a previous poster referred to was that a forked task had no
> ability to retain a scoped variable (eg hold a reference in a static).
>
> Although this has direct applicability in solving issues with a reusable
> buffer - it requires assistance from something like Rusts borrow checker so
> that a reference cannot be retained and only the contents copied - a signal
> to the developer that this is an expensive operation so do you really want
> to do this?


To be honest, I don't really understand what you mean. What I meant is
exactly what Andrew wrote: "override the caller's context, as long as that
context was a parent of the current context".

It is not like a borrow checker. The DI framework I used as an example is
just a way to show where such need would naturally arise. However, the
problem is more general. Consider that you are sharing a resource via SV
(please ignore the fact that I'm not hiding it behind an abstraction for
the sake of the example):

```
ScopedValue<MyResource> resourceRef = ScopedValue.newInstance();
void example() {
  try (var resource = new MyResource()) {
    ScopedValue.where(resourceRef, resource, () -> {
      foo();
    });
  }
}
```

There is nothing special here, `foo` might use the resource shared via an
SV. However, later I might realize that `foo` usually does not need the
resource, so it would be a waste to create it. So, I want to make the
creation of `MyResource` lazy. However, I have problem, because while I
could naively do something like this:

```
ScopedValue<MyLazyResource> resourceRef = ScopedValue.newInstance();
void example() {
  try (var resource = new MyLazyResource()) {
    ScopedValue.where(resourceRef, resource, () -> {
      foo();
    });
  }
}
```

where `MyLazyResource` will create the resource the first time it is
needed, and closes it if it was created. However, there is a problem with
the above code: The scope where `MyResource` is created changed. Even
worse: It is ill-defined now. And this problem would be solvable with my
requested method.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/loom-dev/attachments/20230602/90480888/attachment-0001.htm>


More information about the loom-dev mailing list