/**
     * Sets the result associated with this request context and updates the state accordingly.
     *
     * @param result The result.
     */
    private boolean setResult(final Result result) {
      List<ExtendedResultHandlerHolder<?>> tmpHandlers = null;
      boolean isCancelled = false;
      boolean maySendResult;

      synchronized (stateLock) {
        maySendResult = sendResult;

        switch (state) {
          case PENDING:
          case TOO_LATE:
            /* Switch to appropriate final state. */
            if (!result.getResultCode().equals(ResultCode.CANCELLED)) {
              state = RequestState.RESULT_SENT;
            } else {
              state = RequestState.CANCELLED;
            }
            break;
          case CANCEL_REQUESTED:
            /*
             * Switch to appropriate final state and invoke any cancel
             * request handlers.
             */
            if (!result.getResultCode().equals(ResultCode.CANCELLED)) {
              state = RequestState.RESULT_SENT;
            } else {
              state = RequestState.CANCELLED;
            }

            isCancelled = (state == RequestState.CANCELLED);
            tmpHandlers = cancelResultHandlers;
            cancelResultHandlers = null;
            break;
          case RESULT_SENT:
          case CANCELLED:
            /*
             * This should not happen - could throw an illegal state
             * exception?
             */
            maySendResult = false; // Prevent sending multiple results.
            break;
        }
      }

      /* Invoke handlers outside of lock. */
      if (tmpHandlers != null) {
        for (final ExtendedResultHandlerHolder<?> handler : tmpHandlers) {
          if (isCancelled) {
            handler.handleSuccess();
          } else {
            handler.handleTooLate();
          }
        }
      }

      return maySendResult;
    }