Scoped values polyfill

Davor Hrg hrgdavor at gmail.com
Sun Jan 19 21:11:28 UTC 2025


For others that might be interested,

I have received a suggestion that fits what I need.

------------------------------------------------------------------
I noticed your question on loom-dev, and because I am not registered, I
cannot answer there.

I know one API you can use for that: the opentelemetry context API:
https://javadoc.io/doc/io.opentelemetry/opentelemetry-context/latest/io/opentelemetry/context/Context.html
It's a very small standalone jar, and despite it's root to opentelemetry
(and despite what the javadoc says), it does not depend on the other
opentelemetry APIs, it is a clean isolated small reusable library.

You use it with try-with-resources and it stacks values one on top of the
other (even when reusing the same key).

There is an implementation difference with scoped values: when setting a
new value it keeps the old array of values intact (immutability) and then
does a copy-on-write of the whole array and inserts the new value. See
https://github.com/open-telemetry/opentelemetry-java/blob/main/context/src/main/java/io/opentelemetry/context/ArrayBasedContext.java
Instead, scoped values are chaining the values like a tree (immutable too)
which IMO is a better design when you can have millions of threads.

That said, since the opentelemetry context is extensible, you can emulate
the behavior of scoped values by implementing something else than
ArrayBasedContext if needed. Likewise, you can implement a different
storage than
https://github.com/open-telemetry/opentelemetry-java/blob/main/context/src/main/java/io/opentelemetry/context/ThreadLocalContextStorage.java
should
you need to.

Anyway, I think it does everything that you need. It would be very nice of
you if you could copy my answer to the mailing list to bring awareness to
others (I don't care if you cite me or not).

I hope this helps.

Cheers,
Jean-Noël
-----------------------------------------------------------------------


On Sat, Jan 18, 2025 at 10:11 AM Andrew Haley <aph-open at littlepinkcloud.com>
wrote:

> On 1/17/25 09:08, Davor Hrg wrote:
> > I am looking to see if someone has a workaround that uses ThreadLocals
> in such way that is compatible with scoped values. (I do not need for
> structured concurrency, just a stack inside a single thread)
>
> Sure, you just wrap ThreadLocal.set() and and ThreadLocal.remove() in a
> try-finally. Or doe you need something more than 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
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/loom-dev/attachments/20250119/d91a9141/attachment.htm>


More information about the loom-dev mailing list