Tuesday, 26 January 2021

Java9: Variable Handles

Variable handle is a typed reference to a variable, it support read and write access to the variable under a variety of access modes.

 

What are the supported variable types?

a.   Instance Fields

b.   Static Fields

c.    Arrays

 

How Variables handles are modelled in Java?

Variable Handles are modelled in Java using java.lang.invoke.VarHandle.

 

Goal of Variable Handles

This feature is implemented to standardize the way in which methods of the following classes are invoked.

a.   java.util.concurrent.atomic

b.   sun.misc.Unsafe

 

Let me explain how to update the value of an instance field atomically.

 

public class AtomicCounter {

 

         public int counter = 0;

 

}

 

As you see the definition of AtomicCounter class, it has instance field ‘counter’ which is initialized with value 0.

 

Get the VarHandle reference for counter field.

VarHandle publicIntHandle = MethodHandles.lookup().in(AtomicCounter.class).findVarHandle(AtomicCounter.class,"counter", int.class);

 

Get an instance of ‘AtomicCounter’.

AtomicCounter atomicCounter = new AtomicCounter();

 

Now access the ‘counter’ value associated with ‘atomicCounter’ using publicIntHandle.

int valueOfCounter = (int) publicIntHandle.get(atomicCounter);

 

Now atomically update the 'counter' value of AtomicCounter using getAndSet method of VarHandle.

publicIntHandle.getAndSet(atomicCounter, 10);

 

Find the below working applicaton.

 

AtomicCounter.java

package com.sample.app;

public class AtomicCounter {

	public int counter = 0;

}

 

App.java

package com.sample.app;

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

public class App {
	public static void main(String args[]) throws IOException, NoSuchFieldException, IllegalAccessException {

		VarHandle publicIntHandle = MethodHandles.lookup().in(AtomicCounter.class).findVarHandle(AtomicCounter.class,
				"counter", int.class);

		AtomicCounter atomicCounter = new AtomicCounter();
		int valueOfCounter = (int) publicIntHandle.get(atomicCounter);

		System.out.println("Counter : " + valueOfCounter);

		int prevValue = (int) publicIntHandle.getAndSet(atomicCounter, 10);

		valueOfCounter = (int) publicIntHandle.get(atomicCounter);

		System.out.println("Previous Value : " + prevValue);
		System.out.println("Counter : " + valueOfCounter);

	}
}

 

Output

Counter : 0

Previous Value : 0

Counter : 10

 

 

Reference

https://openjdk.java.net/jeps/193

 

 

 

  

Previous                                                    Next                                                    Home

No comments:

Post a Comment