Compare Exchange: How to Put Compare Exchange Value



Syntax

Method:

public PutCompareExchangeValueOperation(String key, T value, long index)
Parameter Type Description
key String Object identifier under which value is saved, unique in the database scope across the cluster. This string can be up to 512 bytes.
value T The value to be saved for the specified key.
index long * 0 if creating a new key
* The current version of Value when updating a value for an existing key.

Returned object:

public class CompareExchangeResult<T> {
    private T value;
    private long index;
    private boolean successful;

    public T getValue() {
        return value;
    }

    public void setValue(T value) {
        this.value = value;
    }

    public long getIndex() {
        return index;
    }

    public void setIndex(long index) {
        this.index = index;
    }

    public boolean isSuccessful() {
        return successful;
    }

    public void setSuccessful(boolean successful) {
        this.successful = successful;
    }
}
Return Value Type Description
Successful boolean * True if the save operation has completed successfully
* False if the save operation failed
Value T * The value that was saved if operation was successful
* The currently existing value in the server upon failure
Index long * The version number of the value that was saved upon success
* The currently existing version number in the server upon failure

Note:

When calling the 'Put' operation, the index from the request is compared to the index that is currently stored in the server (compare stage).
The value is updated only if the two are equal (exchange stage).

Example I - Create a New Key

CompareExchangeResult<String> compareExchangeResult = store.operations().send(
    new PutCompareExchangeValueOperation<>("Emails/foo@example.org", "users/123", 0));

boolean successful = compareExchangeResult.isSuccessful();
// If successful is true: then Key 'foo@example.org' now has the value of "users/123"

Example II - Update an Existing Key

// Get existing value
CompareExchangeValue<User> readResult
    = store.operations().send(
        new GetCompareExchangeValueOperation<>(User.class, "AdminUser"));

readResult.getValue().setAge(readResult.getValue().getAge() + 1);

// Update value
CompareExchangeResult<User> saveResult
    = store.operations().send(
        new PutCompareExchangeValueOperation<>("AdminUser", readResult.getValue(), readResult.getIndex()));

// The save result is successful only if 'index' wasn't changed between the read and write operations
boolean saveResultSuccessful = saveResult.isSuccessful();