
Working with variable handlers [JEP 193]
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 a 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, the VarHandle.lookup() performs the same operation as those that are performed by a MethodHandle.lookup() method.
The aim of this JEP was to standardize the way in which methods of the following classes are invoked:
- java.util.concurrent.atomic
- sun.misc.Unsafe</li>
Specifically, methods that:
- accessed/mutated object fields
- accessed/mutated elements of an array
In addition, this JEP resulted in two fence operations for memory ordering and object reachability. In the spirit of due diligence, special attention was given to ensure the JVM's safety. 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: Ensure access to an object's field uses identical rules used by:
- getfield byte code
- putfield byte code
- 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.