private static int transferSessionsToDestroy(Collection<WmTezSession> source,
      List<WmTezSession> toDestroy, int deltaSessions) {
    // We were going to kill some queries and reuse the sessions, or maybe restart and put the new
    // ones back into the AM pool. However, the AM pool has shrunk, so we will close them instead.
    if (deltaSessions >= 0) return deltaSessions;
    int toTransfer = Math.min(-deltaSessions, source.size());
    Iterator<WmTezSession> iter = source.iterator();
    for (int i = 0; i < toTransfer; ++i) {
      WmTezSession session = iter.next();
      LOG.debug("Will destroy {} instead of restarting", session);
      if (!session.isIrrelevantForWm()) {
        session.setIsIrrelevantForWm("Killed due to workload management plan change");
      }
      toDestroy.add(session);
      iter.remove();
    }
    return deltaSessions + toTransfer;
  }
This is the main method of the master thread the processes one set of events.
Be mindful of the fact that events can be queued while we are processing events, so
in addition to making sure we keep the current set consistent (e.g. no need to handle
update errors for a session that should already be destroyed), this needs to guard itself
against the future iterations - e.g. what happens if we kill a query due to plan change,
but the DAG finished before the kill happens and the user queues a "return" event? Etc.
DO NOT block for a long time in this method.
@param e Input events.
@param syncWork Output tasks that cannot be called via async methods.
ql/src/java/org/apache/hadoop/hive/ql/exec/tez/WorkloadManager.java