ScopedValue polyfill follow-up [try-with-resources]
Andrew Haley
aph-open at littlepinkcloud.com
Tue Apr 1 09:42:00 UTC 2025
On 3/31/25 23:19, Davor Hrg wrote:
> makeCurrent is not my naming :) ... it is from OpenTelemetry.
>
> my interest in try catch version is because I saw it in OT, but I can live without that variant.
>
> I am trying to integrate ScopedValue patterns into my projects, and am a bit worried it will be in preview in Java 25,
> So I am trying to make something for myself to be easily replaceable by ScopedValues after it is official (not preview).
If you really need to support some property in a try-with-resources
context, you can do this:
private static ThreadLocal<T> CONTEXT;
private static ScopedValue<T> MY_SV;
void makeCurrent(T t) {
CONTEXT.set(t);
}
void apiEntryPoint() {
where(MY_SV, CONTEXT.get()).call(() -> ... stuff ...);
}
That is to say, you can use a thread-local variable to bootstrap a
scoped value, and all callees use the scoped value. This would work
well with structured concurrency.
--
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