Summary
Updates to preview API java.lang.ScopedValue
for JDK 23. The API is proposed to continue as a preview API in this release.
Problem
The ScopedValue.callWhere(Callable)
and ScopedValue.Carrier.call(Callable)
methods take a java.util.concurrent.Callable
operation but this is annoying to use because Callable.call
throws Exception
. The ScopedValue.getWhere(Supplier)
and ScopedValue.Carrier.get(Supplier)
were added to workaround this issue, thus creating two ways to invoke an operation that returns a result.
Solution
Change the parameter for ScopedValue.callWhere
and ScopedValue.Carrier.call
from Callable
to a new functional interface that allows the compiler to infer the exception.
Remove the ScopeValue.getWhere
and ScopedValue.Carrier.get(Supplier)
methods.
More specifically, replace:
ScopedValue.callWhere(ScopedValue, Object, Callable)
ScopedValue.getWhere(ScopedValue, Object, Supplier)
ScopedValue.Carrier.call(Callable)
ScopedValue.Carrier.get(Supplier)
with:
ScopedValue.callWhere(ScopedValue, Object, ScopedValue.CallableOp)
ScopedValue.Carrier.call(ScopedValue.CallableOp)
where ScopedValue.CallableOp
is a functional interface proposed as a preview API.
/**
* An operation that returns a result and may throw an exception.
*
* @param <T> result type of the operation
* @param <X> type of the exception thrown by the operation
* @since 23
*/
@FunctionalInterface
public interface CallableOp<T, X extends Throwable> {
/**
* Executes this operation.
* @return the result, can be null
* @throws X if the operation completes with an exception
*/
T call() throws X;
}
Note that CallableOp
is proposed as a nested class. Most usages of the callWhere
are expected to use lambda expressions so it won't need to be imported. We do not propose to add this to java.util.function
at this time.
Specification
Browsable API docs here: https://cr.openjdk.org/~alanb/sv-20240517/java.base/java/lang/ScopedValue.html
A zip file with the specdiffs is attached although specdiff doesn't easily deal with the changes.
- csr of
-
JDK-8331189 Implementation of Scoped Values (Third Preview)
- Resolved
- relates to
-
JDK-8306573 Implementation of Scoped Values (Preview)
- Closed