Class VarHandle

java.lang.Object
java.lang.invoke.VarHandle

public class VarHandle extends Object
A stub for the VarHandle class.
This stub is used to allow Java 8 release compilation to work as expected. The sole limit of this stub is that since java.lang.invoke is a privileged package it cannot be used at runtime (e.g. loaded by a classloader).

For example, if SomeClass is loaded at runtime:

    class SomeClass {
         private static final VarHandle VH = // ... obtained somehow;

         public static void storeStoreFence() {
             if (VH == null) {
                 return;
             }
             VH.storeStoreFence();
         }
    }
this is not going to work on Java 8.

To fix it is possible to use an holder class (which won't be loaded at runtime):

    class SomeClass {
         static class Holder {
             private static final VarHandle VH = // ... obtained somehow;
         }

         public static void storeStoreFence() {
             VarHandle vh = Holder.VH;
             if (vh == null) {
                 return;
             }
             vh.storeStoreFence();
         }
    }
Or:
    class SomeClass {
         private static final Object VH = // ... obtained somehow;

         public static void storeStoreFence() {
             if (VH == null) {
                 return;
             }
             ((VarHandle)VH).storeStoreFence();
         }
    }
The reason why the methods on the stub are declared as native is to allow MethodHandle.PolymorphicSignature to work as expected, see JLS 15.12.3:
  A method is signature polymorphic if all of the following are true:
  - It is declared in the java.lang.invoke.MethodHandle class or the java.lang.invoke.VarHandle class.
  - It has a single variable arity parameter (ยง8.4.1) whose declared type is Object[].
  - It is native.
This seems counter-intuitive since this stub is not going to be used at runtime, but it is required to allow Java 8 compilation to produce VarHandle's method invocations with parameters and result types with the types of the formal ones of the compile-time declaration.
  • Constructor Details

    • VarHandle

      public VarHandle()
  • Method Details

    • get

      public Object get(Object... args)
    • getAcquire

      public Object getAcquire(Object... args)
    • set

      public void set(Object... args)
    • setRelease

      public void setRelease(Object... args)
    • getAndAdd

      public Object getAndAdd(Object... args)
    • compareAndSet

      public boolean compareAndSet(Object... args)
    • storeStoreFence

      public static void storeStoreFence()