You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@groovy.apache.org by su...@apache.org on 2026/05/01 04:02:44 UTC
(groovy) branch master updated: Minor refactor: extract `ScopedLocal` for thread-scoped value management
This is an automated email from the ASF dual-hosted git repository.
asf-gitbox-commits pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/groovy.git
The following commit(s) were added to refs/heads/master by this push:
new a50aa021ba Minor refactor: extract `ScopedLocal` for thread-scoped value management
a50aa021ba is described below
commit a50aa021ba636dff4b4a26d266e4f959bd35e6b2
Author: Daniel Sun <su...@apache.org>
AuthorDate: Fri May 1 11:55:07 2026 +0900
Minor refactor: extract `ScopedLocal` for thread-scoped value management
---
src/main/java/groovy/concurrent/Pool.java | 4 +-
.../groovy/runtime/async/DefaultAsyncScope.java | 103 +--
.../apache/groovy/runtime/async/DefaultPool.java | 83 +-
.../apache/groovy/runtime/async/ScopedLocal.java | 549 ++++++++++++++
.../groovy/runtime/async/ScopedLocalTest.groovy | 839 +++++++++++++++++++++
5 files changed, 1399 insertions(+), 179 deletions(-)
diff --git a/src/main/java/groovy/concurrent/Pool.java b/src/main/java/groovy/concurrent/Pool.java
index af2dfeae3e..16e49b3aac 100644
--- a/src/main/java/groovy/concurrent/Pool.java
+++ b/src/main/java/groovy/concurrent/Pool.java
@@ -111,8 +111,8 @@ public interface Pool extends Executor, AutoCloseable {
/**
* Returns the pool bound to the current scope, or {@code null}.
* <p>
- * Set by {@link ParallelScope#withPool} using {@code ScopedValue}
- * on JDK 25+ or {@code ThreadLocal} on earlier JDKs.
+ * Set by {@link ParallelScope#withPool} using the runtime's scoped
+ * binding support.
*
* @return the current pool, or {@code null} if none is bound
* @since 6.0.0
diff --git a/src/main/java/org/apache/groovy/runtime/async/DefaultAsyncScope.java b/src/main/java/org/apache/groovy/runtime/async/DefaultAsyncScope.java
index 07aef123c2..e5e376e23f 100644
--- a/src/main/java/org/apache/groovy/runtime/async/DefaultAsyncScope.java
+++ b/src/main/java/org/apache/groovy/runtime/async/DefaultAsyncScope.java
@@ -21,9 +21,6 @@ package org.apache.groovy.runtime.async;
import groovy.concurrent.AsyncScope;
import groovy.concurrent.Awaitable;
-import java.lang.invoke.MethodHandle;
-import java.lang.invoke.MethodHandles;
-import java.lang.invoke.MethodType;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
@@ -53,60 +50,7 @@ import java.util.function.Supplier;
*/
public final class DefaultAsyncScope implements AsyncScope {
- // ---- Scope-tracking: ScopedValue on JDK 25+, ThreadLocal fallback ---
-
- private static final boolean SCOPED_VALUE_AVAILABLE;
- private static final MethodHandle SV_WHERE; // ScopedValue.where(ScopedValue, Object)
- private static final MethodHandle SV_GET; // ScopedValue.get()
- private static final MethodHandle SV_IS_BOUND; // ScopedValue.isBound()
- private static final MethodHandle CARRIER_CALL; // Carrier.call(Callable)
- private static final Object SCOPED_VALUE; // ScopedValue<AsyncScope> instance
- private static final MethodType SCOPED_VALUE_WHERE_TYPE = MethodType.methodType(Object.class, Object.class, AsyncScope.class);
- private static final MethodType SCOPED_VALUE_GET_TYPE = MethodType.methodType(AsyncScope.class, Object.class);
- private static final MethodType SCOPED_VALUE_IS_BOUND_TYPE = MethodType.methodType(boolean.class, Object.class);
- private static final MethodType CARRIER_CALL_TYPE =
- MethodType.methodType(Object.class, Object.class, java.util.concurrent.Callable.class);
-
- private static final ThreadLocal<AsyncScope> CURRENT_TL = new ThreadLocal<>();
-
- static {
- boolean available = false;
- MethodHandle svWhere = null, svGet = null, svIsBound = null, carrierCall = null;
- Object sv = null;
- try {
- Class<?> svClass = Class.forName("java.lang.ScopedValue");
- Class<?> carrierClass = Class.forName("java.lang.ScopedValue$Carrier");
- // ScopedValue.newInstance()
- MethodHandle newInstance = MethodHandles.lookup().findStatic(
- svClass, "newInstance", MethodType.methodType(svClass));
- sv = newInstance.invoke();
- // ScopedValue.where(ScopedValue, Object) -> Carrier
- svWhere = MethodHandles.lookup().findStatic(svClass, "where",
- MethodType.methodType(carrierClass, svClass, Object.class))
- .asType(SCOPED_VALUE_WHERE_TYPE);
- // ScopedValue.get()
- svGet = MethodHandles.lookup().findVirtual(svClass, "get",
- MethodType.methodType(Object.class))
- .asType(SCOPED_VALUE_GET_TYPE);
- // ScopedValue.isBound()
- svIsBound = MethodHandles.lookup().findVirtual(svClass, "isBound",
- MethodType.methodType(boolean.class))
- .asType(SCOPED_VALUE_IS_BOUND_TYPE);
- // Carrier.call(Callable) -> Object
- carrierCall = MethodHandles.lookup().findVirtual(carrierClass, "call",
- MethodType.methodType(Object.class, java.util.concurrent.Callable.class))
- .asType(CARRIER_CALL_TYPE);
- available = true;
- } catch (Throwable ignored) {
- // JDK < 25 — ScopedValue not available
- }
- SCOPED_VALUE_AVAILABLE = available;
- SV_WHERE = svWhere;
- SV_GET = svGet;
- SV_IS_BOUND = svIsBound;
- CARRIER_CALL = carrierCall;
- SCOPED_VALUE = sv;
- }
+ private static final ScopedLocal<AsyncScope> CURRENT_SCOPE = ScopedLocal.newInstance();
private static final int PRUNE_THRESHOLD = 64;
@@ -139,54 +83,19 @@ public final class DefaultAsyncScope implements AsyncScope {
// ---- Static operations ----------------------------------------------
/**
- * Returns the current scope. Uses {@code ScopedValue} on JDK 25+,
- * {@code ThreadLocal} on earlier JDKs.
+ * Returns the current scope, or {@code null} when no scope is bound.
*/
public static AsyncScope current() {
- if (SCOPED_VALUE_AVAILABLE) {
- try {
- if ((boolean) SV_IS_BOUND.invokeExact(SCOPED_VALUE)) {
- return (AsyncScope) SV_GET.invokeExact(SCOPED_VALUE);
- }
- return null;
- } catch (Throwable e) {
- return null;
- }
- }
- return CURRENT_TL.get();
+ return CURRENT_SCOPE.orElse(null);
}
/**
- * Executes the supplier with the given scope as current.
- * Uses {@code ScopedValue.where().call()} on JDK 25+ for
- * optimal virtual thread performance; falls back to
- * {@code ThreadLocal} set/restore on earlier JDKs.
+ * Executes the supplier with the given scope as current,
+ * restoring the previous binding afterwards.
*/
- @SuppressWarnings("unchecked")
public static <T> T withCurrent(AsyncScope scope, Supplier<T> supplier) {
Objects.requireNonNull(supplier, "supplier must not be null");
- if (SCOPED_VALUE_AVAILABLE) {
- try {
- Object carrier = (Object) SV_WHERE.invokeExact(SCOPED_VALUE, scope);
- return (T) CARRIER_CALL.invokeExact(carrier, (java.util.concurrent.Callable<T>) supplier::get);
- } catch (RuntimeException | Error e) {
- throw e;
- } catch (Throwable e) {
- throw new RuntimeException(e);
- }
- }
- // ThreadLocal fallback for JDK 17-24
- AsyncScope previous = CURRENT_TL.get();
- CURRENT_TL.set(scope);
- try {
- return supplier.get();
- } finally {
- if (previous == null) {
- CURRENT_TL.remove();
- } else {
- CURRENT_TL.set(previous);
- }
- }
+ return CURRENT_SCOPE.where(scope, supplier);
}
// ---- Instance methods -----------------------------------------------
diff --git a/src/main/java/org/apache/groovy/runtime/async/DefaultPool.java b/src/main/java/org/apache/groovy/runtime/async/DefaultPool.java
index 43a9924cc0..89c416138f 100644
--- a/src/main/java/org/apache/groovy/runtime/async/DefaultPool.java
+++ b/src/main/java/org/apache/groovy/runtime/async/DefaultPool.java
@@ -59,52 +59,7 @@ public final class DefaultPool implements Pool {
NEW_VT_EXECUTOR = mh;
}
- // ---- Pool.current() tracking: ScopedValue on JDK 25+, ThreadLocal fallback
-
- private static final boolean SCOPED_VALUE_AVAILABLE;
- private static final MethodHandle SV_WHERE;
- private static final MethodHandle SV_GET;
- private static final MethodHandle SV_IS_BOUND;
- private static final MethodHandle CARRIER_CALL;
- private static final Object SCOPED_VALUE;
- private static final ThreadLocal<Pool> CURRENT_TL = new ThreadLocal<>();
- private static final MethodType SCOPED_VALUE_WHERE_TYPE = MethodType.methodType(Object.class, Object.class, Pool.class);
- private static final MethodType SCOPED_VALUE_GET_TYPE = MethodType.methodType(Pool.class, Object.class);
- private static final MethodType SCOPED_VALUE_IS_BOUND_TYPE = MethodType.methodType(boolean.class, Object.class);
- private static final MethodType CARRIER_CALL_TYPE =
- MethodType.methodType(Object.class, Object.class, java.util.concurrent.Callable.class);
-
- static {
- boolean available = false;
- MethodHandle svWhere = null, svGet = null, svIsBound = null, carrierCall = null;
- Object sv = null;
- try {
- Class<?> svClass = Class.forName("java.lang.ScopedValue");
- Class<?> carrierClass = Class.forName("java.lang.ScopedValue$Carrier");
- MethodHandle newInstance = MethodHandles.lookup().findStatic(
- svClass, "newInstance", MethodType.methodType(svClass));
- sv = newInstance.invoke();
- svWhere = MethodHandles.lookup().findStatic(svClass, "where",
- MethodType.methodType(carrierClass, svClass, Object.class))
- .asType(SCOPED_VALUE_WHERE_TYPE);
- svGet = MethodHandles.lookup().findVirtual(svClass, "get",
- MethodType.methodType(Object.class))
- .asType(SCOPED_VALUE_GET_TYPE);
- svIsBound = MethodHandles.lookup().findVirtual(svClass, "isBound",
- MethodType.methodType(boolean.class))
- .asType(SCOPED_VALUE_IS_BOUND_TYPE);
- carrierCall = MethodHandles.lookup().findVirtual(carrierClass, "call",
- MethodType.methodType(Object.class, java.util.concurrent.Callable.class))
- .asType(CARRIER_CALL_TYPE);
- available = true;
- } catch (Throwable ignored) { }
- SCOPED_VALUE_AVAILABLE = available;
- SV_WHERE = svWhere;
- SV_GET = svGet;
- SV_IS_BOUND = svIsBound;
- CARRIER_CALL = carrierCall;
- SCOPED_VALUE = sv;
- }
+ private static final ScopedLocal<Pool> CURRENT_POOL = ScopedLocal.newInstance();
// ---- Instance fields -------------------------------------------------
@@ -177,47 +132,15 @@ public final class DefaultPool implements Pool {
* Returns the pool bound to the current scope, or {@code null}.
*/
public static Pool current() {
- if (SCOPED_VALUE_AVAILABLE) {
- try {
- if ((boolean) SV_IS_BOUND.invokeExact(SCOPED_VALUE)) {
- return (Pool) SV_GET.invokeExact(SCOPED_VALUE);
- }
- return null;
- } catch (Throwable e) {
- return null;
- }
- }
- return CURRENT_TL.get();
+ return CURRENT_POOL.orElse(null);
}
/**
* Executes the supplier with the given pool as current.
*/
- @SuppressWarnings("unchecked")
public static <T> T withCurrent(Pool pool, Supplier<T> supplier) {
Objects.requireNonNull(supplier, "supplier must not be null");
- if (SCOPED_VALUE_AVAILABLE) {
- try {
- Object carrier = (Object) SV_WHERE.invokeExact(SCOPED_VALUE, pool);
- return (T) CARRIER_CALL.invokeExact(carrier,
- (java.util.concurrent.Callable<T>) supplier::get);
- } catch (RuntimeException | Error e) {
- throw e;
- } catch (Throwable e) {
- throw new RuntimeException(e);
- }
- }
- Pool previous = CURRENT_TL.get();
- CURRENT_TL.set(pool);
- try {
- return supplier.get();
- } finally {
- if (previous == null) {
- CURRENT_TL.remove();
- } else {
- CURRENT_TL.set(previous);
- }
- }
+ return CURRENT_POOL.where(pool, supplier);
}
// ---- Pool interface -------------------------------------------------
diff --git a/src/main/java/org/apache/groovy/runtime/async/ScopedLocal.java b/src/main/java/org/apache/groovy/runtime/async/ScopedLocal.java
new file mode 100644
index 0000000000..85043ffaad
--- /dev/null
+++ b/src/main/java/org/apache/groovy/runtime/async/ScopedLocal.java
@@ -0,0 +1,549 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.groovy.runtime.async;
+
+import java.lang.invoke.MethodHandle;
+import java.lang.invoke.MethodHandles;
+import java.lang.invoke.MethodType;
+import java.util.NoSuchElementException;
+import java.util.Objects;
+import java.util.function.Supplier;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+/**
+ * A thread-scoped value holder that abstracts over {@link ThreadLocal}
+ * (JDK < 25) and {@code java.lang.ScopedValue} (JDK 25+),
+ * presenting a unified API modelled after {@code ScopedValue}.
+ *
+ * <h2>Backend selection</h2>
+ * <p>On JDK 25+, where finalized {@code java.lang.ScopedValue} is
+ * available, this class delegates to the {@code ScopedValue} API.
+ * On earlier JDK versions it falls back to a conventional
+ * {@code ThreadLocal} with save-and-restore semantics.</p>
+ *
+ * <h2>API overview</h2>
+ * <p>The API mirrors the main {@code ScopedValue} operations:</p>
+ * <ul>
+ * <li>{@link #get()}, {@link #orElse(Object)}, {@link #orElseThrow(Supplier)},
+ * {@link #isBound()} — query the current binding.</li>
+ * <li>{@link #where(ScopedLocal, Object)} — create a {@link Carrier}
+ * that can bind one or more values for a scoped execution.</li>
+ * <li>{@link Carrier#run(Runnable)}, {@link Carrier#call(Supplier)} —
+ * execute code with the bindings active.</li>
+ * </ul>
+ *
+ * <h2>Usage</h2>
+ * <pre>{@code
+ * private static final ScopedLocal<String> REQUEST_ID =
+ * ScopedLocal.newInstance();
+ *
+ * ScopedLocal.where(REQUEST_ID, "req-42").run(() -> {
+ * assert "req-42".equals(REQUEST_ID.get());
+ * });
+ *
+ * ScopedLocal.where(REQUEST_ID, "req-1")
+ * .where(TENANT_ID, "acme")
+ * .call(() -> handleRequest());
+ *
+ * String result = REQUEST_ID.where("req-7", () -> process());
+ *
+ * private static final ScopedLocal<MyCtx> CTX =
+ * ScopedLocal.withInitial(MyCtx::new);
+ * }</pre>
+ *
+ * @param <T> the type of the scoped value
+ * @since 6.0.0
+ */
+public abstract class ScopedLocal<T> {
+ private static final Logger LOGGER = Logger.getLogger(ScopedLocal.class.getName());
+ private static final String UNBOUND_MESSAGE =
+ "ScopedLocal is not bound and has no initial supplier";
+
+ private static final ScopedValueBindings SCOPED_VALUE_BINDINGS = ScopedValueBindings.detect();
+
+ static final boolean SCOPED_VALUE_AVAILABLE = SCOPED_VALUE_BINDINGS.isAvailable();
+ static final MethodHandle SV_NEW_INSTANCE = SCOPED_VALUE_BINDINGS.newInstanceHandle();
+ static final MethodHandle SV_WHERE = SCOPED_VALUE_BINDINGS.whereHandle();
+ static final MethodHandle SV_GET = SCOPED_VALUE_BINDINGS.getHandle();
+ static final MethodHandle SV_IS_BOUND = SCOPED_VALUE_BINDINGS.isBoundHandle();
+ static final MethodHandle CARRIER_RUN = SCOPED_VALUE_BINDINGS.carrierRunHandle();
+
+ /**
+ * Creates a new {@code ScopedLocal} with no initial value.
+ *
+ * @param <T> the value type
+ * @return a new unbound scoped-local instance
+ */
+ public static <T> ScopedLocal<T> newInstance() {
+ if (SCOPED_VALUE_AVAILABLE) {
+ return new ScopedValueImpl<>();
+ }
+ return new ThreadLocalImpl<>();
+ }
+
+ /**
+ * Creates a new {@code ScopedLocal} whose {@link #get()} method
+ * returns a lazily initialized default when no explicit binding exists.
+ * The supplier is invoked at most once per thread and the result is cached,
+ * analogous to {@link ThreadLocal#withInitial(Supplier)}.
+ *
+ * @param <T> the value type
+ * @param initialSupplier supplies the default value
+ * @return a new scoped-local instance with a default supplier
+ */
+ public static <T> ScopedLocal<T> withInitial(Supplier<? extends T> initialSupplier) {
+ Objects.requireNonNull(initialSupplier, "initialSupplier must not be null");
+ if (SCOPED_VALUE_AVAILABLE) {
+ return new ScopedValueImpl<>(initialSupplier);
+ }
+ return new ThreadLocalImpl<>(initialSupplier);
+ }
+
+ /**
+ * Creates a {@link Carrier} that binds {@code key} to {@code value}.
+ * The binding takes effect when {@link Carrier#run(Runnable)} or
+ * {@link Carrier#call(Supplier)} is invoked.
+ *
+ * @param <T> the value type
+ * @param key the scoped-local to bind
+ * @param value the value to bind; may be {@code null}
+ * @return a carrier holding the binding
+ */
+ public static <T> Carrier where(ScopedLocal<T> key, T value) {
+ Objects.requireNonNull(key, "key must not be null");
+ return new Carrier(key, value, null);
+ }
+
+ /**
+ * Returns the value bound to this scoped-local on the current thread.
+ *
+ * @return the current value
+ * @throws NoSuchElementException if no value is bound and no initial supplier was provided
+ */
+ public abstract T get();
+
+ /**
+ * Returns the value bound to this scoped-local, or {@code other}
+ * if no binding is active and no initial supplier is configured.
+ *
+ * @param other the fallback value
+ * @return the current value or {@code other}
+ */
+ public abstract T orElse(T other);
+
+ /**
+ * Returns the value bound to this scoped-local if available, otherwise throws
+ * an exception produced by the {@code exceptionSupplier}.
+ * <p>
+ * If an initial supplier is configured (via {@link #withInitial(Supplier)}),
+ * this method returns the initial value rather than throwing.
+ *
+ * @param <X> the type of the exception to throw if not bound
+ * @param exceptionSupplier a supplier that produces the exception to throw;
+ * must not be {@code null}
+ * @return the current value
+ * @throws X if no value is bound and no initial supplier is configured
+ * @throws NullPointerException if {@code exceptionSupplier} is {@code null}
+ */
+ public abstract <X extends Throwable> T orElseThrow(Supplier<? extends X> exceptionSupplier) throws X;
+
+ /**
+ * Returns {@code true} if an explicit binding is active or
+ * an initial supplier is configured.
+ *
+ * @return whether a value is available via {@link #get()}
+ */
+ public abstract boolean isBound();
+
+ /**
+ * Binds this scoped-local to {@code value} for the duration of
+ * the supplier, then restores the previous binding.
+ *
+ * @param <R> the result type
+ * @param value the value to bind; may be {@code null}
+ * @param supplier the action to execute with the binding active
+ * @return the supplier's result
+ */
+ public final <R> R where(T value, Supplier<R> supplier) {
+ return ScopedLocal.where(this, value).call(supplier);
+ }
+
+ /**
+ * Binds this scoped-local to {@code value} for the duration of
+ * the action, then restores the previous binding.
+ *
+ * @param value the value to bind; may be {@code null}
+ * @param action the action to execute with the binding active
+ */
+ public final void where(T value, Runnable action) {
+ ScopedLocal.where(this, value).run(action);
+ }
+
+ abstract void bind(Object value, Runnable action);
+
+ @SuppressWarnings("unchecked")
+ static <E extends Throwable> void sneakyThrow(Throwable t) throws E {
+ throw (E) t;
+ }
+
+ /**
+ * An immutable set of scoped-local bindings that can be applied
+ * atomically for the duration of a {@link Runnable} or {@link Supplier}.
+ *
+ * @since 6.0.0
+ */
+ public static final class Carrier {
+ private final ScopedLocal<?> key;
+ private final Object value;
+ private final Carrier prev;
+
+ private Carrier(ScopedLocal<?> key, Object value, Carrier prev) {
+ this.key = key;
+ this.value = value;
+ this.prev = prev;
+ }
+
+ /**
+ * Adds another binding to this carrier, returning a new
+ * carrier that includes all previous bindings plus the new one.
+ *
+ * @param <T> the value type
+ * @param key the scoped-local to bind
+ * @param value the value to bind; may be {@code null}
+ * @return a new carrier with the additional binding
+ */
+ public <T> Carrier where(ScopedLocal<T> key, T value) {
+ Objects.requireNonNull(key, "key must not be null");
+ return new Carrier(key, value, this);
+ }
+
+ /**
+ * Executes the action with all bindings in this carrier active.
+ *
+ * @param action the action to execute
+ */
+ public void run(Runnable action) {
+ Objects.requireNonNull(action, "action must not be null");
+ execute(action);
+ }
+
+ /**
+ * Executes the supplier with all bindings in this carrier active
+ * and returns its result.
+ *
+ * @param <R> the result type
+ * @param supplier the supplier to execute
+ * @return the supplier's result
+ */
+ public <R> R call(Supplier<R> supplier) {
+ Objects.requireNonNull(supplier, "supplier must not be null");
+ Object[] result = new Object[1];
+ execute(() -> result[0] = supplier.get());
+ @SuppressWarnings("unchecked")
+ R value = (R) result[0];
+ return value;
+ }
+
+ private void execute(Runnable action) {
+ Runnable scopedAction = action;
+ for (Carrier carrier = this; carrier != null; carrier = carrier.prev) {
+ ScopedLocal<?> scopedLocal = carrier.key;
+ Object scopedValue = carrier.value;
+ Runnable next = scopedAction;
+ scopedAction = () -> scopedLocal.bind(scopedValue, next);
+ }
+ scopedAction.run();
+ }
+ }
+
+ private static final class ThreadLocalImpl<T> extends ScopedLocal<T> {
+ private static final Object UNSET = new Object();
+ private static final Object NULL_SENTINEL = new Object();
+
+ private final ThreadLocal<Object> delegate = ThreadLocal.withInitial(() -> UNSET);
+ private final Supplier<? extends T> initialSupplier;
+
+ private ThreadLocalImpl() {
+ this.initialSupplier = null;
+ }
+
+ private ThreadLocalImpl(Supplier<? extends T> initialSupplier) {
+ this.initialSupplier = initialSupplier;
+ }
+
+ @Override
+ public T get() {
+ Object value = delegate.get();
+ if (value != UNSET) {
+ return decode(value);
+ }
+ if (initialSupplier != null) {
+ return initializeAndCache();
+ }
+ throw new NoSuchElementException(UNBOUND_MESSAGE);
+ }
+
+ @Override
+ public T orElse(T other) {
+ Object value = delegate.get();
+ if (value != UNSET) {
+ return decode(value);
+ }
+ if (initialSupplier != null) {
+ return initializeAndCache();
+ }
+ return other;
+ }
+
+ @Override
+ public <X extends Throwable> T orElseThrow(Supplier<? extends X> exceptionSupplier) throws X {
+ Objects.requireNonNull(exceptionSupplier, "exceptionSupplier must not be null");
+ Object value = delegate.get();
+ if (value != UNSET) {
+ return decode(value);
+ }
+ if (initialSupplier != null) {
+ return initializeAndCache();
+ }
+ throw exceptionSupplier.get();
+ }
+
+ @Override
+ public boolean isBound() {
+ return delegate.get() != UNSET || initialSupplier != null;
+ }
+
+ @Override
+ void bind(Object value, Runnable action) {
+ Object previous = delegate.get();
+ delegate.set(encode(value));
+ try {
+ action.run();
+ } finally {
+ if (previous == UNSET) {
+ delegate.remove();
+ } else {
+ delegate.set(previous);
+ }
+ }
+ }
+
+ private T initializeAndCache() {
+ T initialValue = initialSupplier.get();
+ delegate.set(encode(initialValue));
+ return initialValue;
+ }
+
+ @SuppressWarnings("unchecked")
+ private T decode(Object value) {
+ return value == NULL_SENTINEL ? null : (T) value;
+ }
+
+ private Object encode(Object value) {
+ return value == null ? NULL_SENTINEL : value;
+ }
+ }
+
+ private static final class ScopedValueImpl<T> extends ScopedLocal<T> {
+ private static final Object NULL_SENTINEL = new Object();
+
+ private final Object scopedValue;
+ private final ThreadLocal<T> fallback;
+
+ private ScopedValueImpl() {
+ this.scopedValue = newScopedValue();
+ this.fallback = null;
+ }
+
+ private ScopedValueImpl(Supplier<? extends T> initialSupplier) {
+ this.scopedValue = newScopedValue();
+ this.fallback = ThreadLocal.withInitial(initialSupplier::get);
+ }
+
+ @Override
+ public T get() {
+ if (isScopedBindingPresent()) {
+ return decode(readScopedValue());
+ }
+ if (fallback != null) {
+ return fallback.get();
+ }
+ throw new NoSuchElementException(UNBOUND_MESSAGE);
+ }
+
+ @Override
+ public T orElse(T other) {
+ if (isScopedBindingPresent()) {
+ return decode(readScopedValue());
+ }
+ if (fallback != null) {
+ return fallback.get();
+ }
+ return other;
+ }
+
+ @Override
+ public <X extends Throwable> T orElseThrow(Supplier<? extends X> exceptionSupplier) throws X {
+ Objects.requireNonNull(exceptionSupplier, "exceptionSupplier must not be null");
+ if (isScopedBindingPresent()) {
+ return decode(readScopedValue());
+ }
+ if (fallback != null) {
+ return fallback.get();
+ }
+ throw exceptionSupplier.get();
+ }
+
+ @Override
+ public boolean isBound() {
+ return isScopedBindingPresent() || fallback != null;
+ }
+
+ @Override
+ void bind(Object value, Runnable action) {
+ try {
+ Object carrier = SV_WHERE.invokeExact(scopedValue, encode(value));
+ CARRIER_RUN.invokeExact(carrier, action);
+ } catch (Throwable t) {
+ sneakyThrow(t);
+ }
+ }
+
+ private boolean isScopedBindingPresent() {
+ try {
+ return (boolean) SV_IS_BOUND.invokeExact(scopedValue);
+ } catch (Throwable t) {
+ sneakyThrow(t);
+ return false;
+ }
+ }
+
+ private Object readScopedValue() {
+ try {
+ return SV_GET.invokeExact(scopedValue);
+ } catch (Throwable t) {
+ sneakyThrow(t);
+ return null;
+ }
+ }
+
+ @SuppressWarnings("unchecked")
+ private T decode(Object value) {
+ return value == NULL_SENTINEL ? null : (T) value;
+ }
+
+ private Object encode(Object value) {
+ return value == null ? NULL_SENTINEL : value;
+ }
+
+ private static Object newScopedValue() {
+ try {
+ return SV_NEW_INSTANCE.invokeExact();
+ } catch (Throwable t) {
+ throw new IllegalStateException("Unable to initialize ScopedValue backend", t);
+ }
+ }
+ }
+
+ private static final class ScopedValueBindings {
+ private final boolean available;
+ private final MethodHandle newInstance;
+ private final MethodHandle where;
+ private final MethodHandle get;
+ private final MethodHandle isBound;
+ private final MethodHandle carrierRun;
+
+ private ScopedValueBindings(boolean available, MethodHandle newInstance, MethodHandle where,
+ MethodHandle get, MethodHandle isBound, MethodHandle carrierRun) {
+ this.available = available;
+ this.newInstance = newInstance;
+ this.where = where;
+ this.get = get;
+ this.isBound = isBound;
+ this.carrierRun = carrierRun;
+ }
+
+ private static ScopedValueBindings detect() {
+ if (Runtime.version().feature() < 25) {
+ return unavailable();
+ }
+
+ try {
+ Class<?> scopedValueClass = Class.forName("java.lang.ScopedValue");
+ Class<?> carrierClass = Class.forName("java.lang.ScopedValue$Carrier");
+ MethodHandles.Lookup lookup = MethodHandles.publicLookup();
+
+ MethodHandle newInstance = lookup.findStatic(scopedValueClass, "newInstance",
+ MethodType.methodType(scopedValueClass))
+ .asType(MethodType.methodType(Object.class));
+ MethodHandle where = lookup.findStatic(scopedValueClass, "where",
+ MethodType.methodType(carrierClass, scopedValueClass, Object.class))
+ .asType(MethodType.methodType(Object.class, Object.class, Object.class));
+ MethodHandle get = lookup.findVirtual(scopedValueClass, "get",
+ MethodType.methodType(Object.class))
+ .asType(MethodType.methodType(Object.class, Object.class));
+ MethodHandle isBound = lookup.findVirtual(scopedValueClass, "isBound",
+ MethodType.methodType(boolean.class))
+ .asType(MethodType.methodType(boolean.class, Object.class));
+ MethodHandle carrierRun = lookup.findVirtual(carrierClass, "run",
+ MethodType.methodType(void.class, Runnable.class))
+ .asType(MethodType.methodType(void.class, Object.class, Runnable.class));
+
+ return new ScopedValueBindings(true, newInstance, where, get, isBound, carrierRun);
+ } catch (Throwable t) {
+ if (LOGGER.isLoggable(Level.FINE)) {
+ LOGGER.log(Level.FINE,
+ "ScopedValue not available on JDK " + Runtime.version().feature()
+ + "; using ThreadLocal fallback",
+ t);
+ }
+ return unavailable();
+ }
+ }
+
+ private static ScopedValueBindings unavailable() {
+ return new ScopedValueBindings(false, null, null, null, null, null);
+ }
+
+ private boolean isAvailable() {
+ return available;
+ }
+
+ private MethodHandle newInstanceHandle() {
+ return newInstance;
+ }
+
+ private MethodHandle whereHandle() {
+ return where;
+ }
+
+ private MethodHandle getHandle() {
+ return get;
+ }
+
+ private MethodHandle isBoundHandle() {
+ return isBound;
+ }
+
+ private MethodHandle carrierRunHandle() {
+ return carrierRun;
+ }
+ }
+}
diff --git a/src/test/groovy/org/apache/groovy/runtime/async/ScopedLocalTest.groovy b/src/test/groovy/org/apache/groovy/runtime/async/ScopedLocalTest.groovy
new file mode 100644
index 0000000000..e142a7b5f6
--- /dev/null
+++ b/src/test/groovy/org/apache/groovy/runtime/async/ScopedLocalTest.groovy
@@ -0,0 +1,839 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.groovy.runtime.async
+
+import org.junit.jupiter.api.DisplayName
+import org.junit.jupiter.api.Nested
+import org.junit.jupiter.api.Test
+import org.junit.jupiter.api.Timeout
+
+import java.lang.invoke.MethodType
+import java.util.concurrent.CountDownLatch
+import java.util.concurrent.CyclicBarrier
+import java.util.concurrent.TimeUnit
+import java.util.concurrent.atomic.AtomicInteger
+import java.util.concurrent.atomic.AtomicReference
+import java.util.function.Supplier
+
+import static org.junit.jupiter.api.Assertions.*
+
+/**
+ * Comprehensive unit tests for {@link ScopedLocal}.
+ *
+ * @since 6.0.0
+ */
+@DisplayName('ScopedLocal')
+@Timeout(10)
+class ScopedLocalTest {
+
+ @Test
+ @DisplayName('ScopedValue backend is selected on JDK 25+')
+ void testBackendSelection() {
+ int jdkVersion = Runtime.version().feature()
+ boolean expected = jdkVersion >= 25
+ assertEquals(expected, ScopedLocal.SCOPED_VALUE_AVAILABLE,
+ "SCOPED_VALUE_AVAILABLE should be $expected on JDK $jdkVersion")
+ }
+
+ @Test
+ @DisplayName('MethodHandles are adapted for invokeExact on JDK 25+')
+ void testMethodHandleTypesAdaptedForInvokeExact() {
+ if (!ScopedLocal.SCOPED_VALUE_AVAILABLE) return
+
+ assertEquals(
+ MethodType.methodType(Object),
+ ScopedLocal.SV_NEW_INSTANCE.type(),
+ 'SV_NEW_INSTANCE must return Object (adapted from ScopedValue)')
+
+ assertEquals(
+ MethodType.methodType(Object, Object, Object),
+ ScopedLocal.SV_WHERE.type(),
+ 'SV_WHERE must accept (Object, Object) and return Object')
+
+ assertEquals(
+ MethodType.methodType(Object, Object),
+ ScopedLocal.SV_GET.type(),
+ 'SV_GET must accept (Object) and return Object')
+
+ assertEquals(
+ MethodType.methodType(boolean, Object),
+ ScopedLocal.SV_IS_BOUND.type(),
+ 'SV_IS_BOUND must accept (Object) and return boolean')
+
+ assertEquals(
+ MethodType.methodType(void, Object, Runnable),
+ ScopedLocal.CARRIER_RUN.type(),
+ 'CARRIER_RUN must accept (Object, Runnable) and return void')
+ }
+
+ @Test
+ @DisplayName('invokeExact calls work end-to-end through ScopedLocal API')
+ void testInvokeExactEndToEnd() {
+ def sl = ScopedLocal.<String>newInstance()
+ assertFalse(sl.isBound())
+ assertEquals('fb', sl.orElse('fb'))
+
+ ScopedLocal.where(sl, 'hello').run {
+ assertTrue(sl.isBound())
+ assertEquals('hello', sl.get())
+ assertEquals('hello', sl.orElse('other'))
+ }
+ }
+
+ @Test
+ @DisplayName('invokeExact calls work with withInitial supplier')
+ void testInvokeExactWithInitial() {
+ def sl = ScopedLocal.withInitial { 'default' }
+ assertTrue(sl.isBound())
+ assertEquals('default', sl.get())
+
+ ScopedLocal.where(sl, 'override').run {
+ assertEquals('override', sl.get())
+ }
+
+ assertEquals('default', sl.get())
+ }
+
+ @Nested
+ @DisplayName('Accessors (no initial supplier)')
+ class AccessorsNoInitial {
+
+ @Test
+ @DisplayName('get() throws NoSuchElementException when unbound')
+ void testGetUnbound() {
+ def sl = ScopedLocal.<String>newInstance()
+ assertThrows(NoSuchElementException) { sl.get() }
+ }
+
+ @Test
+ @DisplayName('orElse() returns fallback when unbound')
+ void testOrElseUnbound() {
+ def sl = ScopedLocal.<String>newInstance()
+ assertEquals('fallback', sl.orElse('fallback'))
+ }
+
+ @Test
+ @DisplayName('orElse() returns null fallback when unbound')
+ void testOrElseNullFallback() {
+ def sl = ScopedLocal.<String>newInstance()
+ assertNull(sl.orElse(null))
+ }
+
+ @Test
+ @DisplayName('isBound() returns false when unbound')
+ void testIsBoundUnbound() {
+ def sl = ScopedLocal.<String>newInstance()
+ assertFalse(sl.isBound())
+ }
+
+ @Test
+ @DisplayName('get() returns bound value inside where()')
+ void testGetBound() {
+ def sl = ScopedLocal.<String>newInstance()
+ def result = ScopedLocal.where(sl, 'hello').call { sl.get() }
+ assertEquals('hello', result)
+ }
+
+ @Test
+ @DisplayName('orElse() returns bound value (not fallback) inside where()')
+ void testOrElseBound() {
+ def sl = ScopedLocal.<String>newInstance()
+ def result = ScopedLocal.where(sl, 'hello').call { sl.orElse('fallback') }
+ assertEquals('hello', result)
+ }
+
+ @Test
+ @DisplayName('isBound() returns true inside where()')
+ void testIsBoundInside() {
+ def sl = ScopedLocal.<String>newInstance()
+ ScopedLocal.where(sl, 'x').run { assertTrue(sl.isBound()) }
+ }
+
+ @Test
+ @DisplayName('get() throws again after where() scope exits')
+ void testGetAfterScopeExit() {
+ def sl = ScopedLocal.<String>newInstance()
+ ScopedLocal.where(sl, 'temp').run { }
+ assertThrows(NoSuchElementException) { sl.get() }
+ }
+ }
+
+ @Nested
+ @DisplayName('Accessors (with initial supplier)')
+ class AccessorsWithInitial {
+
+ @Test
+ @DisplayName('get() returns initial value when unbound')
+ void testGetInitial() {
+ def sl = ScopedLocal.withInitial { 'default' }
+ assertEquals('default', sl.get())
+ }
+
+ @Test
+ @DisplayName('orElse() returns initial value (not fallback) when unbound')
+ void testOrElseInitial() {
+ def sl = ScopedLocal.withInitial { 'default' }
+ assertEquals('default', sl.orElse('fallback'))
+ }
+
+ @Test
+ @DisplayName('isBound() returns true when initial supplier is present')
+ void testIsBoundInitial() {
+ def sl = ScopedLocal.withInitial { 'default' }
+ assertTrue(sl.isBound())
+ }
+
+ @Test
+ @DisplayName('get() returns bound value, not initial, inside where()')
+ void testGetBoundOverridesInitial() {
+ def sl = ScopedLocal.withInitial { 'default' }
+ def result = ScopedLocal.where(sl, 'override').call { sl.get() }
+ assertEquals('override', result)
+ }
+
+ @Test
+ @DisplayName('get() restores to initial value after where() exits')
+ void testGetRestoredToInitial() {
+ def sl = ScopedLocal.withInitial { 'default' }
+ ScopedLocal.where(sl, 'override').run { }
+ assertEquals('default', sl.get())
+ }
+
+ @Test
+ @DisplayName('initial supplier is lazily invoked')
+ void testLazyInitialization() {
+ def counter = new AtomicInteger(0)
+ def sl = ScopedLocal.withInitial {
+ counter.incrementAndGet()
+ 'lazy'
+ }
+ assertEquals(0, counter.get(), 'supplier must not be called at creation')
+ assertEquals('lazy', sl.get())
+ assertEquals(1, counter.get(), 'supplier called on first access')
+ }
+
+ @Test
+ @DisplayName('initial value is cached after first access')
+ void testInitialValueCached() {
+ def counter = new AtomicInteger(0)
+ def sl = ScopedLocal.withInitial {
+ counter.incrementAndGet()
+ 'cached'
+ }
+ sl.get()
+ sl.get()
+ sl.get()
+ assertEquals(1, counter.get(), 'supplier should only be called once per thread')
+ }
+
+ @Test
+ @DisplayName('withInitial(null) throws NullPointerException')
+ void testWithInitialNull() {
+ assertThrows(NullPointerException) {
+ ScopedLocal.withInitial(null)
+ }
+ }
+
+ @Test
+ @DisplayName('initial supplier is per-thread')
+ void testPerThreadInitial() {
+ def threadName = new AtomicReference<String>()
+ def sl = ScopedLocal.withInitial { Thread.currentThread().name }
+
+ def latch = new CountDownLatch(1)
+ Thread.start('worker-initial') {
+ threadName.set(sl.get())
+ latch.countDown()
+ }
+ latch.await(5, TimeUnit.SECONDS)
+
+ def mainValue = sl.get()
+ assertTrue(mainValue.contains(Thread.currentThread().name) || mainValue != null)
+ assertEquals('worker-initial', threadName.get())
+ }
+ }
+
+ @Nested
+ @DisplayName('orElseThrow')
+ class OrElseThrowTests {
+
+ @Test
+ @DisplayName('orElseThrow() throws supplier exception when unbound')
+ void testOrElseThrowUnbound() {
+ def sl = ScopedLocal.<String>newInstance()
+ def ex = assertThrows(IllegalStateException) {
+ sl.orElseThrow { new IllegalStateException('not bound') }
+ }
+ assertEquals('not bound', ex.message)
+ }
+
+ @Test
+ @DisplayName('orElseThrow() returns bound value when bound')
+ void testOrElseThrowBound() {
+ def sl = ScopedLocal.<String>newInstance()
+ def result = ScopedLocal.where(sl, 'hello').call {
+ sl.orElseThrow { new IllegalStateException('should not throw') }
+ }
+ assertEquals('hello', result)
+ }
+
+ @Test
+ @DisplayName('orElseThrow() returns initial value when withInitial and unbound')
+ void testOrElseThrowWithInitial() {
+ def sl = ScopedLocal.withInitial { 'default' }
+ def result = sl.orElseThrow { new IllegalStateException('should not throw') }
+ assertEquals('default', result)
+ }
+
+ @Test
+ @DisplayName('orElseThrow() returns scoped value, not initial, when both present')
+ void testOrElseThrowScopedOverridesInitial() {
+ def sl = ScopedLocal.withInitial { 'default' }
+ def result = ScopedLocal.where(sl, 'override').call {
+ sl.orElseThrow { new IllegalStateException('should not throw') }
+ }
+ assertEquals('override', result)
+ }
+
+ @Test
+ @DisplayName('orElseThrow() restores throw behaviour after scope exits')
+ void testOrElseThrowAfterScopeExit() {
+ def sl = ScopedLocal.<String>newInstance()
+ ScopedLocal.where(sl, 'temp').run { }
+ assertThrows(IllegalStateException) {
+ sl.orElseThrow { new IllegalStateException('gone') }
+ }
+ }
+
+ @Test
+ @DisplayName('orElseThrow() returns null binding, not throw')
+ void testOrElseThrowNullBinding() {
+ def sl = ScopedLocal.<String>newInstance()
+ def result = ScopedLocal.where(sl, null).call {
+ sl.orElseThrow { new IllegalStateException('should not throw') }
+ }
+ assertNull(result)
+ }
+
+ @Test
+ @DisplayName('orElseThrow(null) throws NullPointerException')
+ void testOrElseThrowNullSupplier() {
+ def sl = ScopedLocal.<String>newInstance()
+ assertThrows(NullPointerException) {
+ sl.orElseThrow(null)
+ }
+ }
+
+ @Test
+ @DisplayName('orElseThrow() propagates checked exception type')
+ void testOrElseThrowCheckedExceptionType() {
+ def sl = ScopedLocal.<String>newInstance()
+ try {
+ sl.orElseThrow { new IOException('checked') }
+ fail('should have thrown')
+ } catch (IOException e) {
+ assertEquals('checked', e.message)
+ }
+ }
+
+ @Test
+ @DisplayName('orElseThrow() with withInitial returning null does not throw')
+ void testOrElseThrowWithInitialReturningNull() {
+ def sl = ScopedLocal.withInitial { null }
+ def result = sl.orElseThrow { new IllegalStateException('should not throw') }
+ assertNull(result)
+ }
+ }
+
+ @Nested
+ @DisplayName('Null bindings')
+ class NullBindings {
+
+ @Test
+ @DisplayName('where(null) makes get() return null')
+ void testBindNull() {
+ def sl = ScopedLocal.<String>newInstance()
+ def result = ScopedLocal.where(sl, null).call { sl.get() }
+ assertNull(result)
+ }
+
+ @Test
+ @DisplayName('isBound() returns true for null binding')
+ void testIsBoundNull() {
+ def sl = ScopedLocal.<String>newInstance()
+ ScopedLocal.where(sl, null).run {
+ assertTrue(sl.isBound())
+ }
+ }
+
+ @Test
+ @DisplayName('orElse() returns null (not fallback) for null binding')
+ void testOrElseNull() {
+ def sl = ScopedLocal.<String>newInstance()
+ def result = ScopedLocal.where(sl, null).call { sl.orElse('fallback') }
+ assertNull(result)
+ }
+
+ @Test
+ @DisplayName('where(null) with withInitial returns null, not initial value')
+ void testNullOverridesInitial() {
+ def sl = ScopedLocal.withInitial { 'default' }
+ def result = ScopedLocal.where(sl, null).call { sl.get() }
+ assertNull(result, 'null binding must override the initial value')
+ }
+
+ @Test
+ @DisplayName('after where(null) exits, withInitial restores to initial value')
+ void testNullScopeRestoresInitial() {
+ def sl = ScopedLocal.withInitial { 'default' }
+ ScopedLocal.where(sl, null).run { }
+ assertEquals('default', sl.get())
+ }
+ }
+
+ @Nested
+ @DisplayName('Nested bindings')
+ class NestedBindings {
+
+ @Test
+ @DisplayName('inner where() shadows outer where()')
+ void testNestedShadowing() {
+ def sl = ScopedLocal.<String>newInstance()
+ ScopedLocal.where(sl, 'outer').run {
+ assertEquals('outer', sl.get())
+ ScopedLocal.where(sl, 'inner').run {
+ assertEquals('inner', sl.get())
+ }
+ assertEquals('outer', sl.get())
+ }
+ }
+
+ @Test
+ @DisplayName('three levels of nesting restore correctly')
+ void testTripleNesting() {
+ def sl = ScopedLocal.<Integer>newInstance()
+ def trace = []
+ ScopedLocal.where(sl, 1).run {
+ trace << sl.get()
+ ScopedLocal.where(sl, 2).run {
+ trace << sl.get()
+ ScopedLocal.where(sl, 3).run {
+ trace << sl.get()
+ }
+ trace << sl.get()
+ }
+ trace << sl.get()
+ }
+ assertEquals([1, 2, 3, 2, 1], trace)
+ }
+
+ @Test
+ @DisplayName('null binding nested inside non-null binding')
+ void testNullNestedInNonNull() {
+ def sl = ScopedLocal.<String>newInstance()
+ ScopedLocal.where(sl, 'outer').run {
+ assertEquals('outer', sl.get())
+ ScopedLocal.where(sl, null).run {
+ assertNull(sl.get())
+ }
+ assertEquals('outer', sl.get())
+ }
+ }
+
+ @Test
+ @DisplayName('non-null binding nested inside null binding')
+ void testNonNullNestedInNull() {
+ def sl = ScopedLocal.<String>newInstance()
+ ScopedLocal.where(sl, null).run {
+ assertNull(sl.get())
+ ScopedLocal.where(sl, 'inner').run {
+ assertEquals('inner', sl.get())
+ }
+ assertNull(sl.get())
+ }
+ }
+ }
+
+ @Nested
+ @DisplayName('Carrier')
+ class CarrierTests {
+
+ @Test
+ @DisplayName('Carrier.run() executes action with binding')
+ void testCarrierRun() {
+ def sl = ScopedLocal.<String>newInstance()
+ def seen = new AtomicReference<String>()
+ ScopedLocal.where(sl, 'via-carrier').run {
+ seen.set(sl.get())
+ }
+ assertEquals('via-carrier', seen.get())
+ }
+
+ @Test
+ @DisplayName('Carrier.call() returns supplier result')
+ void testCarrierCall() {
+ def sl = ScopedLocal.<String>newInstance()
+ def result = ScopedLocal.where(sl, 'hello').call { sl.get().toUpperCase() }
+ assertEquals('HELLO', result)
+ }
+
+ @Test
+ @DisplayName('Carrier.call() can return null')
+ void testCarrierCallReturnsNull() {
+ def sl = ScopedLocal.<String>newInstance()
+ def result = ScopedLocal.where(sl, 'x').call { null }
+ assertNull(result)
+ }
+
+ @Test
+ @DisplayName('chained where() binds multiple ScopedLocals')
+ void testCarrierChaining() {
+ def sl1 = ScopedLocal.<String>newInstance()
+ def sl2 = ScopedLocal.<Integer>newInstance()
+ def result = ScopedLocal.where(sl1, 'alpha')
+ .where(sl2, 42)
+ .call { sl1.get() + ':' + sl2.get() }
+ assertEquals('alpha:42', result)
+ }
+
+ @Test
+ @DisplayName('chained where() with same key uses last binding')
+ void testCarrierChainSameKey() {
+ def sl = ScopedLocal.<String>newInstance()
+ def result = ScopedLocal.where(sl, 'first')
+ .where(sl, 'second')
+ .call { sl.get() }
+ assertEquals('second', result)
+ }
+
+ @Test
+ @DisplayName('chained bindings are all restored after scope exits')
+ void testCarrierChainingRestoration() {
+ def sl1 = ScopedLocal.<String>newInstance()
+ def sl2 = ScopedLocal.<String>newInstance()
+
+ ScopedLocal.where(sl1, 'A').where(sl2, 'B').run { }
+
+ assertFalse(sl1.isBound())
+ assertFalse(sl2.isBound())
+ }
+
+ @Test
+ @DisplayName('where(key, null) throws NullPointerException for null key')
+ void testCarrierNullKey() {
+ assertThrows(NullPointerException) {
+ ScopedLocal.where(null, 'value')
+ }
+ }
+
+ @Test
+ @DisplayName('Carrier.run(null) throws NullPointerException')
+ void testCarrierRunNull() {
+ def sl = ScopedLocal.<String>newInstance()
+ assertThrows(NullPointerException) {
+ ScopedLocal.where(sl, 'x').run(null)
+ }
+ }
+
+ @Test
+ @DisplayName('Carrier.call(null) throws NullPointerException')
+ void testCarrierCallNull() {
+ def sl = ScopedLocal.<String>newInstance()
+ assertThrows(NullPointerException) {
+ ScopedLocal.where(sl, 'x').call(null)
+ }
+ }
+ }
+
+ @Nested
+ @DisplayName('Convenience instance methods')
+ class ConvenienceMethods {
+
+ @Test
+ @DisplayName('instance where(value, Supplier) works')
+ void testInstanceWhereSupplier() {
+ def sl = ScopedLocal.<String>newInstance()
+ def result = sl.where('val', { sl.get() } as Supplier)
+ assertEquals('val', result)
+ }
+
+ @Test
+ @DisplayName('instance where(value, Runnable) works')
+ void testInstanceWhereRunnable() {
+ def sl = ScopedLocal.<String>newInstance()
+ def seen = new AtomicReference<String>()
+ sl.where('val', { seen.set(sl.get()) } as Runnable)
+ assertEquals('val', seen.get())
+ }
+ }
+
+ @Nested
+ @DisplayName('Exception propagation')
+ class ExceptionPropagation {
+
+ @Test
+ @DisplayName('RuntimeException propagates transparently from run()')
+ void testRuntimeExceptionRun() {
+ def sl = ScopedLocal.<String>newInstance()
+ def ex = assertThrows(IllegalStateException) {
+ ScopedLocal.where(sl, 'x').run {
+ throw new IllegalStateException('boom')
+ }
+ }
+ assertEquals('boom', ex.message)
+ }
+
+ @Test
+ @DisplayName('RuntimeException propagates transparently from call()')
+ void testRuntimeExceptionCall() {
+ def sl = ScopedLocal.<String>newInstance()
+ def ex = assertThrows(IllegalArgumentException) {
+ ScopedLocal.where(sl, 'x').call {
+ throw new IllegalArgumentException('bad arg')
+ }
+ }
+ assertEquals('bad arg', ex.message)
+ }
+
+ @Test
+ @DisplayName('Error propagates transparently')
+ void testErrorPropagation() {
+ def sl = ScopedLocal.<String>newInstance()
+ assertThrows(StackOverflowError) {
+ ScopedLocal.where(sl, 'x').run {
+ throw new StackOverflowError('overflow')
+ }
+ }
+ }
+
+ @Test
+ @DisplayName('checked exception propagates via sneaky throw')
+ void testCheckedExceptionSneakyThrow() {
+ def sl = ScopedLocal.<String>newInstance()
+ try {
+ ScopedLocal.where(sl, 'x').run {
+ throw new IOException('io error')
+ }
+ fail('should have thrown')
+ } catch (IOException e) {
+ assertEquals('io error', e.message)
+ }
+ }
+
+ @Test
+ @DisplayName('binding is restored after exception in run()')
+ void testBindingRestoredAfterException() {
+ def sl = ScopedLocal.<String>newInstance()
+ ScopedLocal.where(sl, 'outer').run {
+ try {
+ ScopedLocal.where(sl, 'inner').run {
+ throw new RuntimeException('fail')
+ }
+ } catch (RuntimeException ignored) {
+ }
+ assertEquals('outer', sl.get(), 'outer binding must be restored')
+ }
+ }
+
+ @Test
+ @DisplayName('binding is restored after exception in call()')
+ void testBindingRestoredAfterExceptionCall() {
+ def sl = ScopedLocal.<String>newInstance()
+ ScopedLocal.where(sl, 'outer').run {
+ try {
+ ScopedLocal.where(sl, 'inner').call {
+ throw new RuntimeException('fail')
+ }
+ } catch (RuntimeException ignored) {
+ }
+ assertEquals('outer', sl.get())
+ }
+ }
+
+ @Test
+ @DisplayName('exception from chained carrier propagates and restores all bindings')
+ void testChainedCarrierException() {
+ def sl1 = ScopedLocal.<String>newInstance()
+ def sl2 = ScopedLocal.<Integer>newInstance()
+
+ assertThrows(RuntimeException) {
+ ScopedLocal.where(sl1, 'a').where(sl2, 1).run {
+ throw new RuntimeException('chained fail')
+ }
+ }
+
+ assertFalse(sl1.isBound())
+ assertFalse(sl2.isBound())
+ }
+ }
+
+ @Nested
+ @DisplayName('Thread isolation')
+ class ThreadIsolation {
+
+ @Test
+ @DisplayName('bindings are thread-local, not shared')
+ void testThreadIsolation() {
+ def sl = ScopedLocal.<String>newInstance()
+ def barrier = new CyclicBarrier(2)
+ def otherSeen = new AtomicReference<Boolean>()
+
+ ScopedLocal.where(sl, 'main-value').run {
+ def thread = Thread.start {
+ otherSeen.set(sl.isBound())
+ barrier.await(5, TimeUnit.SECONDS)
+ }
+ barrier.await(5, TimeUnit.SECONDS)
+ thread.join(5000)
+ }
+
+ assertFalse(otherSeen.get(), 'binding must not leak to another thread')
+ }
+
+ @Test
+ @DisplayName('concurrent where() on same ScopedLocal from different threads')
+ void testConcurrentBindings() {
+ def sl = ScopedLocal.<Integer>newInstance()
+ int threadCount = 8
+ def barrier = new CyclicBarrier(threadCount)
+ def results = new AtomicReference<List>(Collections.synchronizedList([]))
+ def latch = new CountDownLatch(threadCount)
+
+ (0..<threadCount).each { int i ->
+ Thread.start {
+ ScopedLocal.where(sl, i).run {
+ barrier.await(5, TimeUnit.SECONDS)
+ results.get() << sl.get()
+ latch.countDown()
+ }
+ }
+ }
+
+ assertTrue(latch.await(10, TimeUnit.SECONDS))
+ def sorted = results.get().sort()
+ assertEquals((0..<threadCount).toList(), sorted,
+ 'each thread must see its own bound value')
+ }
+
+ @Test
+ @DisplayName('withInitial creates independent instances per thread')
+ void testWithInitialPerThread() {
+ def counter = new AtomicInteger(0)
+ def sl = ScopedLocal.withInitial { counter.incrementAndGet() }
+
+ int threadCount = 4
+ def latch = new CountDownLatch(threadCount)
+ def values = Collections.synchronizedList([])
+
+ (0..<threadCount).each {
+ Thread.start {
+ values << sl.get()
+ latch.countDown()
+ }
+ }
+
+ assertTrue(latch.await(5, TimeUnit.SECONDS))
+ assertEquals(threadCount, values.toSet().size(),
+ 'each thread must get an independent initial value')
+ }
+ }
+
+ @Nested
+ @DisplayName('Edge cases')
+ class EdgeCases {
+
+ @Test
+ @DisplayName('where() with same value as current is a no-op semantically')
+ void testRebindSameValue() {
+ def sl = ScopedLocal.<String>newInstance()
+ ScopedLocal.where(sl, 'same').run {
+ def result = ScopedLocal.where(sl, 'same').call { sl.get() }
+ assertEquals('same', result)
+ }
+ }
+
+ @Test
+ @DisplayName('empty Runnable in run() does not throw')
+ void testEmptyRunnable() {
+ def sl = ScopedLocal.<String>newInstance()
+ ScopedLocal.where(sl, 'x').run { }
+ }
+
+ @Test
+ @DisplayName('Carrier is immutable — original not affected by chaining')
+ void testCarrierImmutability() {
+ def sl1 = ScopedLocal.<String>newInstance()
+ def sl2 = ScopedLocal.<Integer>newInstance()
+
+ def carrier1 = ScopedLocal.where(sl1, 'a')
+ def carrier2 = carrier1.where(sl2, 42)
+
+ carrier1.run {
+ assertEquals('a', sl1.get())
+ assertFalse(sl2.isBound())
+ }
+
+ carrier2.run {
+ assertEquals('a', sl1.get())
+ assertEquals(42, sl2.get())
+ }
+ }
+
+ @Test
+ @DisplayName('deeply nested binding and restoration')
+ void testDeeplyNested() {
+ def sl = ScopedLocal.<Integer>newInstance()
+ int depth = 100
+ Runnable innermost = {
+ assertEquals(depth, sl.get())
+ }
+
+ Runnable current = innermost
+ for (int i = depth; i >= 1; i--) {
+ int val = i
+ Runnable next = current
+ current = {
+ ScopedLocal.where(sl, val).run {
+ assertEquals(val, sl.get())
+ next.run()
+ assertEquals(val, sl.get())
+ }
+ }
+ }
+ current.run()
+ assertFalse(sl.isBound())
+ }
+
+ @Test
+ @DisplayName('withInitial supplier returning null is handled correctly')
+ void testWithInitialReturningNull() {
+ def sl = ScopedLocal.withInitial { null }
+ assertNull(sl.get(), 'initial supplier returning null should yield null')
+ assertTrue(sl.isBound(), 'should be considered bound with initial supplier')
+ }
+
+ @Test
+ @DisplayName('call() result is returned even when value is bound to null')
+ void testCallWithNullBinding() {
+ def sl = ScopedLocal.<String>newInstance()
+ def result = ScopedLocal.where(sl, null).call { 'computed' }
+ assertEquals('computed', result)
+ }
+ }
+}