Working with variable handlers

Variable handlers are typed references to variables and are governed by the java.lang.invoke.VarHandle abstract class. The VarHandle method's signature is polymorphic. This provides for great variability in both method signatures and return types. Here is a code sample demonstrating how VarHandle might be used:

. . .
class Example {
int myInt;
. . .
}
. . .
class Sample {
static final VarHandle VH_MYINT;

static {
try {
VH_MYINT =
MethodHandles.lookup().in(Example.class)
.findVarHandle(Example.class, "myInt", int.class);
}
catch (Exception e) {
throw new Error(e);
}
}
}
. . .

As you can see in the preceding code snippet, VarHandle.lookup() performs the same operation as those that are performed by a MethodHandle.lookup() method.

The aim of this change to the Java platform was to standardize the way in which methods of the following classes are invoked:

  • java.util.concurrent.atomic
  • sun.misc.Unsafe

Specifically, methods that did the following:

  • Accessed/mutated object fields
  • Accessed/mutated elements of an array

In addition, this change resulted in two fence operations for memory ordering and object reachability. In the spirit of due diligence, special attention was given to ensure the safety of the JVM. It was important to ensure that memory errors did not result from these changes. Data integrity, usability, and, of course, performance were key components of the aforementioned due diligence and are explained as follows:

  • Safety: Corrupt memory states must not be possible.
  • Data integrity: It must be ensured that access to an object's field uses identical rules:
  • getfield bytecode
  • putfield bytecode
  • Usability: The benchmark for usability was the sun.misc.Unsafe API. The goal was to make the new API easier to use than the benchmark.
  • Performance: There could be no degradation of performance compared to the use of the sun.misc.Unsafe API. The goal was to outperform that API.
In Java, a fence operation is what javac does to force a constraint on memory in the form of a barrier instruction. These operations occur before and after the barrier instruction, essentially fencing them in.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset