简体   繁体   中英

Couchbase backoff with Java API

I'm trying to understand how incremental backoff works in the Java Couchbase API. The following code snippet is from the Couchbase Java Tutorial (I have added a few comments).

public OperationFuture<Boolean> contSet(String key,
                                        int exp,
                                        Object value,
                                        int tries) {
  OperationFuture<Boolean> result = null;
  OperationStatus status;
  int backoffexp = 0;

  try {
    do {
      if (backoffexp > tries) {
        throw new RuntimeException("Could not perform a set after "
                + tries + " tries.");
      }
      result = cbc.set(key, exp, value);
      status = result.getStatus(); // Is this a blocking call?
      if (status.isSuccess()) {
        break;
      }
      if (backoffexp > 0) {
        double backoffMillis = Math.pow(2, backoffexp);
        backoffMillis = Math.min(1000, backoffMillis); // 1 sec max
        Thread.sleep((int) backoffMillis);
        System.err.println("Backing off, tries so far: " + backoffexp);
      }
      backoffexp++;

      // Why are we checking again if the operation previously failed
      if (!status.isSuccess()) {
        System.err.println("Failed with status: " + status.getMessage());
      }

    // If we break on success, why not do while(true)?
    } while (status.getMessage().equals("Temporary failure"));
  } catch (InterruptedException ex) {
    System.err.println("Interrupted while trying to set.  Exception:"
            + ex.getMessage());
  }

  if (result == null) {
    throw new RuntimeException("Could not carry out operation.");
  }

  return result;
}

Do calls to getStatus() return only when the operation has either succeeded or failed? (ie synchronous). The Java Tutorial seem to say it is blocking, but the Java API says:

Get the current status of this operation. Note that the operation status may change as the operation is tried and potentially retried against the servers specified by the NodeLocator.

Why do we need to check status.isSuccess() multiple times? If it was successful we would have broken out of the loop, and we can assume it has failed?

If there any reason to do while (status.getMessage().equals("Temporary failure")) instead of while(true) , since we call break when the status is successful?

Thanks

getStatus() forces the Future to complete (ie internally calls get() , so the status of the operation can be known. To put it another way, there is no such thing as a pending status in the APU, so you must force the Future to complete to be able to determine is status.

See the source code of Operation_Future:getStatus for details.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM