Implementing VarHandle

David M. Lloyd david.lloyd at
Tue Apr 14 12:08:55 UTC 2015

On 04/14/2015 05:17 AM, Remi Forax wrote:
> On 04/14/2015 10:38 AM, MacGregor, Duncan (GE Energy Management) wrote:
>> On 12/04/2015 15:54, "Remi Forax" <forax at> wrote:
>>> Hi guys,
>>> I was about to write a blog post explaining why i don't like the way
>>> VarHandle are currently implemented when it occurs to me that providing
>>> another implementation may be a more efficient to discuss about
>>> implementation.
>>> So my implementation is here,
>>> the API is typesafe, the implementation is runtime safe and i get mostly
>>> the same assembly code using unsafe or this VarHandle API.
>>> The idea is that there is no need to add more polymorphic signature
>>> methods, a good old Java method is enough if it using a method handle
>>> under the hood.
>>> All the logic is described using method handles and the only logic
>>> written in Java is
>>> 1) when to create such method handle (the first time a method is
>>> called),
>>>      it works like invokedynamic but the method handles are stable
>>> instead of being constant.
>>> 2) how to link all things together to do nullcheck, atomic operation and
>>> post operation (like fence or sum).
>> Although I agree regarding the type safety of this being better than the
>> polymorphic signatures of the current VarHandle API, this doesn¹t feel
>> like it has the right shape. How would your API expand to handle user
>> defined value types? I think if we want something type safe then
>> specialisation over type variables would be a much better path forward
>> for
>> this, assuming the two can be lined up in when they might be delivered
>> into the main JDK.
>> Regards, Duncan.
> Hi Duncan,
> in my opinion, there are two different issues,
> one is to provide a safe API for doing things people currently do with
> Unsafe,
> the other is the support of value type for some of these operations.
> The prototype i have written is good to do the former but not the later.
> Supporting value type will require 3 things:
>    - being able to declare a type variable as any, like you can do with
> the vahalla compiler
>    - adding support of value types in the method handle API, exactly
> being able
>      to invoke a method handle with a value type as parameter.
>    - adding support of value types in Unsafe
> If you know the answer to the last point, everything else will fold.
> Before that, I think we can deliver an API that does a CAS in a safe way
> without directly using sun.misc.Unsafe.
> BTW, perhaps we do not need a new API but just change the implementation
> of the classes of java.util.concurrent.atomic.

Someone (I forget who) had an interesting prototype for 
Atomic*FieldUpdater that generated classes for each field (I think it 
was field), which also allows real type safety.  That seemed like a 
really good approach to me.


More information about the valhalla-dev mailing list