How to create static VarHandle in Java 9?

JavaObject Oriented ProgrammingProgramming

VarHandle is a reference to a variable, and it provides access to variables under various access modes (such as plain read/write, volatile read/write, and compare-and-swap), similar to the functionality provided by java.util.concurrent.atomic and sun.misc.Unsafe. The variables can be array elements, instance or static fields in a class.

In the below example, we can create a static variable handle.

Example

import java.lang.invoke.MethodHandles;
import java.lang.invoke.VarHandle;

public class StaticVarHandleTest {
   static int field;
   static int[] array = new int[20];
   static final VarHandle FIELD, ARRAY;
   static {
      try {
         FIELD = MethodHandles.lookup().in(StaticVarHandleTest.class).findStaticVarHandle(StaticVarHandleTest.class, "field", Integer.TYPE);
         ARRAY = MethodHandles.arrayElementVarHandle(int[].class);
      } catch(Exception e) {
         throw new InternalError(e);
      }
   }
   public static void main(String args[]) throws Exception {
      int i = (int)FIELD.getVolatile();
      System.out.println(i);
      FIELD.getAndAdd(5);
      System.out.println(field);
      System.out.println(ARRAY.getAndAdd(array, 5, 5));
      System.out.println(ARRAY.getAndAdd(array, 5, 5));
   }
}

Output

0
5
0
5
raja
Published on 17-Apr-2020 09:25:14
Advertisements