public UserEntity safelyUpdateUserEntity(UserEntity userEntity, Command command, int maxRetries) {
    int retriesLeft = maxRetries;

    do {
      try {
        command.perform(userEntity);
        userDAO.merge(userEntity);

        // The merge was a success, break out of this loop and return
        return userEntity;
      } catch (Throwable t) {
        Throwable cause = t;
        int failSafe = 50; // counter to ensure the following do/while loop does not loop indefinitely

        do {
          if (cause instanceof OptimisticLockException) {
            // An OptimisticLockException was caught, refresh the entity and retry.
            Integer userID = userEntity.getUserId();

            // Find the userEntity record to make sure the object is managed by JPA.  The passed-in
            // object may be detached, therefore calling reset on it will fail.
            userEntity = userDAO.findByPK(userID);

            if (userEntity == null) {
              LOG.warn("Failed to find user with user id of {}.  The user may have been removed. Aborting.", userID);
              return null;  // return since this user is no longer available.
            }

            retriesLeft--;

            // The the number of attempts has been exhausted, re-throw the exception
            if (retriesLeft == 0) {
              LOG.error("Failed to update the user's ({}) consecutive failures value due to an OptimisticLockException.  Aborting.",
                  userEntity.getUserName());
              throw t;
            } else {
              LOG.warn("Failed to update the user's ({}) consecutive failures value due to an OptimisticLockException.  {} retries left, retrying...",
                  userEntity.getUserName(), retriesLeft);
            }

            break;
          } else {
            // Get the cause to see if it is an OptimisticLockException
            cause = cause.getCause();
          }

          // decrement the failsafe counter to ensure we do not get stuck in an infinite loop.
          failSafe--;
        } while ((cause != null) && (cause != t) && (failSafe > 0)); // We are out of causes

        if ((cause == null) || (cause == t) || failSafe == 0) {
          throw t;
        }
      }
    } while (retriesLeft > 0); // We are out of retries

    return userEntity;
  }
Attempts to update the specified {@link UserEntity} while handling {@link OptimisticLockException}s
by obtaining the latest version of the {@link UserEntity} and retrying the operation.

If the maximum number of retries is exceeded, then the operation will fail by rethrowing the last
exception encountered.


@param userEntity the user entity
@param command  a command to perform on the user entity object that changes it state thus needing
                to be persisted
@param maxRetries the maximum number of reties to peform before failing
ambari-server/src/main/java/org/apache/ambari/server/security/authorization/Users.java