Direct use of jli.ConstantBootstraps to obtain VarHandles and JEP 303

Johannes Kuhn info at j-kuhn.de
Sun May 24 19:27:12 UTC 2020


I noticed that I can simplify my code by using 
jli.ConstantBootstraps.fieldVarHandle instead of Lookup.findVarHandle.

Instead of this:

     private volatile long myVar = 0;
     private static final VarHandle MY_VAR;
     static {
         try {
             MY_VAR = 
MethodHandles.lookup().findVarHandle(MyVHTest.class, "myVar",
                     long.class);
         } catch (ReflectiveOperationException e) {
             throw new ExceptionInInitializerError(e);
         }
     }

I can simply write

     private volatile long myVar;
     private static final VarHandle MY_VAR = 
ConstantBootstraps.fieldVarHandle(
             MethodHandles.lookup(), "myVar", VarHandle.class, 
MyVHTest.class, long.class);

I know, ConstantBootstraps were not designed for that use case - as 
evident of the duplication of VarHandle.class as parameter.

I am also not the first one to write such a construct. 
sun.nio.ch.SelectionKeyImpl uses ConstantBootstraps to obtain a 
VarHandle as well.

This brought up some connection to JEP 303: Intrinsics for the LDC and 
INVOKEDYNAMIC Instructions in my head.

The questions that I did ask myself were:
* Could this be compiled into a constant dynamic instruction?
* If yes, should this only be done for ConstantBootstraps or any method 
with take a Lookup, String, Class as first 3 parameters?
* If everyone: What if people start to rely on it for performance - and 
a change to their code would turn the LDC into a normal call?
* Is it even worth the cost? Or is this a model that is worth pursuing?

While technically possible, I don't think that compiling methods outside 
of ConstantBootstraps is a good idea.
The JEP 303 proposal has at least a fail fast mode - either everything 
is a TC or it can't be compiled.

I'm probably stretching Brian Goetz's definition of valuable feedback a bit:
"We tried to use this feature in this situation, and those are the 
things that did work and those are the things that didn't." [1]
I guess, it's "I tried to use ConstantBootstaps instead of a Class 
initializer, and it did work".

-Johannes

PS.:  @Brian Goetz: Thank you for answering a lot of questions during 
the stream. It's was (and still is) very informative.

[1]: https://www.twitch.tv/videos/629358245?t=15h49m42s



More information about the amber-dev mailing list