private synchronized void checkTaskCompletion() {
    if (taskStateMachine.getState().isDone()) {
      return;
    }

    // are there more partition splits expected?
    if (partitionedDriverFactory != null && !partitionedDriverFactory.isNoMoreSplits()) {
      return;
    }
    // do we still have running tasks?
    if (remainingDrivers.get() != 0) {
      return;
    }

    // no more output will be created
    sharedBuffer.finish();

    // are there still pages in the output buffer
    if (!sharedBuffer.isFinished()) {
      return;
    }

    // Cool! All done!
    taskStateMachine.finished();
  }
  @Override
  public synchronized void addResultQueue(OutputBuffers outputBuffers) {
    checkNotNull(outputBuffers, "outputBuffers is null");

    try (SetThreadName setThreadName = new SetThreadName("Task-%s", taskId)) {
      sharedBuffer.setOutputBuffers(outputBuffers);
    }
  }
  @Override
  public BufferResult getResults(
      String outputId, long startingSequenceId, DataSize maxSize, Duration maxWait)
      throws InterruptedException {
    checkNotNull(outputId, "outputId is null");
    checkArgument(maxSize.toBytes() > 0, "maxSize must be at least 1 byte");
    checkNotNull(maxWait, "maxWait is null");
    checkState(
        !Thread.holdsLock(this),
        "Can not get result data while holding a lock on the %s",
        getClass().getSimpleName());

    try (SetThreadName setThreadName = new SetThreadName("Task-%s", taskId)) {
      return sharedBuffer.get(outputId, startingSequenceId, maxSize, maxWait);
    }
  }
  @Override
  public TaskInfo getTaskInfo(boolean full) {
    try (SetThreadName setThreadName = new SetThreadName("Task-%s", taskId)) {
      checkTaskCompletion();

      TaskState state = taskStateMachine.getState();
      List<ExecutionFailureInfo> failures = ImmutableList.of();
      if (state == TaskState.FAILED) {
        failures = toFailures(taskStateMachine.getFailureCauses());
      }

      return new TaskInfo(
          taskStateMachine.getTaskId(),
          nextTaskInfoVersion.getAndIncrement(),
          state,
          location,
          lastHeartbeat.get(),
          sharedBuffer.getInfo(),
          getNoMoreSplits(),
          taskContext.getTaskStats(),
          failures);
    }
  }
 @Override
 public void abortResults(String outputId) {
   try (SetThreadName setThreadName = new SetThreadName("Task-%s", taskId)) {
     sharedBuffer.abort(outputId);
   }
 }
  private SqlTaskExecution(
      Session session,
      TaskId taskId,
      URI location,
      PlanFragment fragment,
      OutputBuffers outputBuffers,
      LocalExecutionPlanner planner,
      DataSize maxBufferSize,
      TaskExecutor taskExecutor,
      DataSize maxTaskMemoryUsage,
      DataSize operatorPreAllocatedMemory,
      QueryMonitor queryMonitor,
      Executor notificationExecutor,
      boolean cpuTimerEnabled) {
    try (SetThreadName setThreadName = new SetThreadName("Task-%s", taskId)) {
      this.taskId = checkNotNull(taskId, "taskId is null");
      this.location = checkNotNull(location, "location is null");
      this.taskExecutor = checkNotNull(taskExecutor, "driverExecutor is null");
      this.notificationExecutor =
          checkNotNull(notificationExecutor, "notificationExecutor is null");

      this.taskStateMachine = new TaskStateMachine(taskId, notificationExecutor);
      taskStateMachine.addStateChangeListener(
          new StateChangeListener<TaskState>() {
            @Override
            public void stateChanged(TaskState taskState) {
              if (taskState.isDone()) {
                SqlTaskExecution.this.taskExecutor.removeTask(taskHandle);
                // make sure buffers are cleaned up
                if (taskState != TaskState.FAILED) {
                  // don't close buffers for a failed query
                  // closed buffers signal to upstream tasks that everything finished cleanly
                  sharedBuffer.destroy();
                }
              }
            }
          });

      this.taskContext =
          new TaskContext(
              taskStateMachine,
              notificationExecutor,
              session,
              checkNotNull(maxTaskMemoryUsage, "maxTaskMemoryUsage is null"),
              checkNotNull(operatorPreAllocatedMemory, "operatorPreAllocatedMemory is null"),
              cpuTimerEnabled);

      this.sharedBuffer =
          new SharedBuffer(
              taskId,
              notificationExecutor,
              checkNotNull(maxBufferSize, "maxBufferSize is null"),
              outputBuffers);
      sharedBuffer.addStateChangeListener(
          new StateChangeListener<QueueState>() {
            @Override
            public void stateChanged(QueueState taskState) {
              if (taskState == QueueState.FINISHED) {
                checkTaskCompletion();
              }
            }
          });

      this.queryMonitor = checkNotNull(queryMonitor, "queryMonitor is null");

      taskHandle = taskExecutor.addTask(taskId);

      LocalExecutionPlan localExecutionPlan =
          planner.plan(
              session,
              fragment.getRoot(),
              fragment.getSymbols(),
              new TaskOutputFactory(sharedBuffer));
      List<DriverFactory> driverFactories = localExecutionPlan.getDriverFactories();

      // index driver factories
      DriverSplitRunnerFactory partitionedDriverFactory = null;
      ImmutableList.Builder<DriverSplitRunnerFactory> unpartitionedDriverFactories =
          ImmutableList.builder();
      for (DriverFactory driverFactory : driverFactories) {
        if (driverFactory.getSourceIds().contains(fragment.getPartitionedSource())) {
          checkState(
              partitionedDriverFactory == null, "multiple partitioned sources are not supported");
          partitionedDriverFactory = new DriverSplitRunnerFactory(driverFactory);
        } else {
          unpartitionedDriverFactories.add(new DriverSplitRunnerFactory(driverFactory));
        }
      }
      this.unpartitionedDriverFactories = unpartitionedDriverFactories.build();

      if (fragment.getDistribution() == PlanDistribution.SOURCE) {
        checkArgument(
            partitionedDriverFactory != null,
            "Fragment is partitioned, but no partitioned driver found");
      }
      this.partitionedSourceId = fragment.getPartitionedSource();
      this.partitionedDriverFactory = partitionedDriverFactory;
    }
  }
  private SqlTaskExecution(
      TaskStateMachine taskStateMachine,
      TaskContext taskContext,
      SharedBuffer sharedBuffer,
      PlanFragment fragment,
      LocalExecutionPlanner planner,
      TaskExecutor taskExecutor,
      QueryMonitor queryMonitor,
      Executor notificationExecutor) {
    this.taskStateMachine = checkNotNull(taskStateMachine, "taskStateMachine is null");
    this.taskId = taskStateMachine.getTaskId();
    this.taskContext = checkNotNull(taskContext, "taskContext is null");
    this.sharedBuffer = checkNotNull(sharedBuffer, "sharedBuffer is null");

    this.taskExecutor = checkNotNull(taskExecutor, "driverExecutor is null");
    this.notificationExecutor = checkNotNull(notificationExecutor, "notificationExecutor is null");

    this.queryMonitor = checkNotNull(queryMonitor, "queryMonitor is null");

    try (SetThreadName ignored = new SetThreadName("Task-%s", taskId)) {
      List<DriverFactory> driverFactories;
      try {
        OutputFactory outputOperatorFactory;
        if (fragment.getOutputPartitioning() == OutputPartitioning.NONE) {
          outputOperatorFactory = new TaskOutputFactory(sharedBuffer);
        } else if (fragment.getOutputPartitioning() == OutputPartitioning.HASH) {
          outputOperatorFactory = new PartitionedOutputFactory(sharedBuffer);
        } else {
          throw new PrestoException(
              NOT_SUPPORTED,
              format("OutputPartitioning %s is not supported", fragment.getOutputPartitioning()));
        }

        LocalExecutionPlan localExecutionPlan =
            planner.plan(
                taskContext.getSession(),
                fragment.getRoot(),
                fragment.getOutputLayout(),
                fragment.getSymbols(),
                fragment.getDistribution(),
                outputOperatorFactory);
        driverFactories = localExecutionPlan.getDriverFactories();
      } catch (Throwable e) {
        // planning failed
        taskStateMachine.failed(e);
        throw Throwables.propagate(e);
      }

      // index driver factories
      DriverSplitRunnerFactory partitionedDriverFactory = null;
      ImmutableList.Builder<DriverSplitRunnerFactory> unpartitionedDriverFactories =
          ImmutableList.builder();
      for (DriverFactory driverFactory : driverFactories) {
        if (driverFactory.getSourceIds().contains(fragment.getPartitionedSource())) {
          checkState(
              partitionedDriverFactory == null, "multiple partitioned sources are not supported");
          partitionedDriverFactory = new DriverSplitRunnerFactory(driverFactory);
        } else {
          unpartitionedDriverFactories.add(new DriverSplitRunnerFactory(driverFactory));
        }
      }
      this.unpartitionedDriverFactories = unpartitionedDriverFactories.build();

      if (fragment.getDistribution() == PlanDistribution.SOURCE) {
        checkArgument(
            partitionedDriverFactory != null,
            "Fragment is partitioned, but no partitioned driver found");
      }
      this.partitionedSourceId = fragment.getPartitionedSource();
      this.partitionedDriverFactory = partitionedDriverFactory;

      // don't register the task if it is already completed (most likely failed during planning
      // above)
      if (!taskStateMachine.getState().isDone()) {
        taskHandle = taskExecutor.addTask(taskId);
        taskStateMachine.addStateChangeListener(
            new RemoveTaskHandleWhenDone(taskExecutor, taskHandle));
      } else {
        taskHandle = null;
      }

      sharedBuffer.addStateChangeListener(
          new CheckTaskCompletionOnBufferFinish(SqlTaskExecution.this));
    }
  }