A newer version of this documentation is available.

View Latest

Concurrent Document Mutations

    +

    Unresolved include directive in modules/howtos/pages/concurrent-document-mutations.adoc - include::6.5@sdk:shared:partial$cas.adoc[]

    Unresolved include directive in modules/howtos/pages/concurrent-document-mutations.adoc - include::6.5@sdk:shared:partial$cas.adoc[]

    Unresolved include directive in modules/howtos/pages/concurrent-document-mutations.adoc - include::6.5@sdk:shared:partial$cas.adoc[]

    Unresolved include directive in modules/howtos/pages/concurrent-document-mutations.adoc - include::6.5@sdk:shared:partial$cas.adoc[]

    int maxRetries = 10;
    
    for (int i = 0; i < maxRetries; i++) {
      // Get the current document contents
      GetResult getResult = collection.get("user-id");
    
      // Increment a count on the user
      JsonObject content = getResult.contentAsObject();
      content.put("visitCount", content.getLong("visitCount") + 1);
    
      try {
        // Attempt to replace the document with cas
        collection.replace("user-id", content, replaceOptions().cas(getResult.cas()));
        break;
      } catch (CasMismatchException ex) {
        // continue the loop on cas mismatch to try again
        // note that any other exception will be raised and break the loop as well
      }
    }

    Sometimes more logic is needed when performing updates, for example, if a property is mutually exclusive with another property; only one or the other can exist, but not both.

    Unresolved include directive in modules/howtos/pages/concurrent-document-mutations.adoc - include::6.5@sdk:shared:partial$cas.adoc[]

    Unresolved include directive in modules/howtos/pages/concurrent-document-mutations.adoc - include::6.5@sdk:shared:partial$cas.adoc[]

    Unresolved include directive in modules/howtos/pages/concurrent-document-mutations.adoc - include::6.5@sdk:shared:partial$cas.adoc[]

    GetResult getAndLockResult = collection.getAndLock("key", Duration.ofSeconds(2));
    
    long lockedCas = getAndLockResult.cas();
    
    /* an example of simply unlocking the document:
    collection.unlock("key", lockedCas);
     */
    
    collection.replace("key", "new value", replaceOptions().cas(lockedCas));

    The handler will unlock the item either via an explicit unlock operation (unlock) or implicitly via modifying the item with the correct CAS.

    If the item has already been locked, the server will respond with CasMismatch which means that the operation could not be executed temporarily, but may succeed later on.