New candidate JEP: 506: Scoped Values

Andrew Haley aph-open at littlepinkcloud.com
Sat Apr 19 08:06:18 UTC 2025


On 19/04/2025 06:23, Davor Hrg wrote:
> I was wondering, if I create a library that uses scoped value,
> and for some reason I am unable to prevent the user from running something without providing the scoped value.
> 
> Is there a performance hit if I set up a static method that would guard .get() and throw a more descriptive
> error to what needs to be done to use the library correctly ?
> 
> If there is a performance hit, it would be nice to be able to define additional custom message when
> scoped value is not present and an error is thrown.

I don't think that there will be a significant performance hit. Class
ScopedValue was written to perform well with the HotSpot C2 compiler,
so I don't believe you will see significant slowdowns from checking
isBound() before get().

The test you should run on your own hardware to verify this is
ScopedValues.thousandMaybeGets:

     @Benchmark
     @OutputTimeUnit(TimeUnit.NANOSECONDS)
     public int thousandMaybeGets(Blackhole bh) throws Exception {
         int result = 0;
         for (int i = 0; i < 1_000; i++) {
             if (ScopedValuesData.sl1.isBound()) {
                 result += ScopedValuesData.sl1.get();
             }
         }
         return result;
     }

The result I get is:

Benchmark                                  Mode  Cnt   Score    Error  Units
ScopedValues.thousandMaybeGets             avgt   10  22.832 ±  0.005  ns/op

Which is to say, the loop above runs in 23ns.

If the scoped value is not bound this test will run more slowly, but I
imagine that you'll throw an exception the first time that you detect
that the value is not bound.

Andrew.



More information about the loom-dev mailing list