IgniteAtomicReference

The IgniteAtomicReference interface provides an object reference variable that can be read and written atomically. 

We can define a reference with an initial value as follows: 

IgniteAtomicReference<String> ref = ignite.atomicReference("myRef", // atomic Reference name.
"myValue", // Initial value for atomic reference.
true // Create if it does not exist.
);

We defined a string reference, but you can define any type of your choice. One important method of IgniteAtomicReference is compareAndSet(T expVal, T newVal). This method conditionally sets the new value if expVal is equal to the current value. This behavior is similar to optimistic locking: when you update a value, you must have the most recent object. If anyone updated it after you read the value, then you can't change the value.

The following example demonstrates that behavior. We create the object with myValue, now trying to update the value but passing old value as notMyValue; hence, the existing value and my expValue won't match:

System.out.println("did it update? " + ref.compareAndSet("notMyValue", "new Value")
+ " , the ref value is -" + ref.get());

Here, we have expValue="myValue", which is the current reference value. Hence, the reference value will be changed to "new Value":

System.out.println("did it update? " + ref.compareAndSet("myValue", "new Value") + " , the ref value is -"  + ref.get());

Here is the output:

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

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