Scoped variables
Andrew Haley
aph at redhat.com
Sat Dec 8 09:26:45 UTC 2018
On 12/7/18 6:15 PM, dean.long at oracle.com wrote:> Now might be a good time to start a discussion on how we want scoped
> variables to be created and named. With ThreadLocals, there is a
> constructor and I can create as many unique instances as I want in the
> heap and store those instances in the instance fields of other objects.
> However with scoped variables, do we really need something so general?
I think not. We want something as simple and lightweight as
possible, surely?
Let's say we had something like a final ScopedValue<T> class
with bind() and get() methods.
So, to declare a ScopedValue you'd have something like
static final ScopedValue<int> val = ScopedValue.newInstance();
and to bind it
try (val.bind(42)) { // Try with reources-like syntax, for example
... stuff ...
}
and to access it
val.get()
ScopedValues should be immutable for the resons described in this
thread. In particular, a fiber should inherit ScopedValue
bindings at the point it calves from its mother thread. If the
block in which a value is bound exits while another fiber is still
excuting, that's fine because the fiber inherits the values of
those bindings, not a reference to something mutable.
Is there any thing else? I don't think so. And we have a pretty
good idea how to do that efficiently. I know that there will be
some concern about the cost of copying ScopedValue bindings into
a new fiber or continuation, but as far as I know it's the only
semantics that makes sense and allows us to reason about binding
lifetimes.
> What if a scoped variable looked more like a static final field, a
> method variable, or a constant pool constant? Some of the uses of
> ThreadLocal that seem like good candidates for scoped variables are only
> using a single "local" per class (or even package or module).
Indeed so.
> There are some good reasons for making these variables look like
> constants. So here's a possibly crazy idea: What if the names of
> scoped variables looked more like the enum constants in a Java enum
> type: constant singleton instances associated with a class by name.
Sure, why not? That would make things even simpler.
--
Andrew Haley
Java Platform Lead Engineer
Red Hat UK Ltd. <https://www.redhat.com>
EAC8 43EB D3EF DB98 CC77 2FAD A5CD 6035 332F A671
More information about the loom-dev
mailing list