Perform the work of processing the various OperationContext.Stage queues, and then the DONE stage.
346775
private void processStages() {

        // Locate the next step to execute.
        ModelNode primaryResponse = null;
        Step step;
        do {
            step = steps.get(currentStage).pollFirst();
            if (step == null) {

                if (currentStage == Stage.MODEL && addModelValidationSteps()) {
                    continue;
                }
                // No steps remain in this stage; give subclasses a chance to check status
                // and approve moving to the next stage
                if (!tryStageCompleted(currentStage)) {
                    // Can't continue
                    resultAction = ResultAction.ROLLBACK;
                    executeResultHandlerPhase(null);
                    return;
                }
                // Proceed to the next stage
                if (currentStage.hasNext()) {
                    currentStage = currentStage.next();
                    if (currentStage == Stage.VERIFY) {
                        // a change was made to the runtime. Thus, we must wait
                        // for stability before resuming in to verify.
                        try {
                            awaitServiceContainerStability();
                        } catch (InterruptedException e) {
                            cancelled = true;
                            handleContainerStabilityFailure(primaryResponse, e);
                            executeResultHandlerPhase(null);
                            return;
                        }  catch (TimeoutException te) {
                            // The service container is in an unknown state; but we don't require restart
                            // because rollback may allow the container to stabilize. We force require-restart
                            // in the rollback handling if the container cannot stabilize (see OperationContextImpl.releaseStepLocks)
                            //processState.setRestartRequired();  // don't use our restartRequired() method as this is not reversible in rollback
                            handleContainerStabilityFailure(primaryResponse, te);
                            executeResultHandlerPhase(null);
                            return;
                        }
                    }
                }
            } else {
                // The response to the first step is what goes to the outside caller
                if (primaryResponse == null) {
                    primaryResponse = step.response;
                }
                // Execute the step, but make sure we always finalize any steps
                Throwable toThrow = null;
                // Whether to return after try/finally
                boolean exit = false;
                try {
                    CapabilityRegistry.RuntimeStatus stepStatus = getStepExecutionStatus(step);
                    if (stepStatus == RuntimeCapabilityRegistry.RuntimeStatus.NORMAL) {
                        executeStep(step);
                    } else {
                        String header = stepStatus == RuntimeCapabilityRegistry.RuntimeStatus.RESTART_REQUIRED
                                ? OPERATION_REQUIRES_RESTART : OPERATION_REQUIRES_RELOAD;
                        step.response.get(RESPONSE_HEADERS, header).set(true);
                    }
                } catch (RuntimeException | Error re) {
                    resultAction = ResultAction.ROLLBACK;
                    toThrow = re;
                } finally {
                    // See if executeStep put us in a state where we shouldn't do any more
                    if (toThrow != null || !canContinueProcessing()) {
                        // We're done.
                        executeResultHandlerPhase(toThrow);
                        exit = true; // we're on the return path
                    }
                }
                if (exit) {
                    return;
                }
            }
        } while (currentStage != Stage.DONE);

        assert primaryResponse != null; // else ModelControllerImpl executed an op with no steps

        // All steps ran and canContinueProcessing returned true for the last one, so...
        executeDoneStage(primaryResponse);
    }
1260651
def perform_ops(self):
        
        with self.db:
            with closing(self.db.cursor()) as cursor:
                cursor.execute('BEGIN TRANSACTION')
                self._perform_ops(cursor)
769719
final void performAction(final AbstractEventQueue eventQueue, final Event<?> event) {
        final Event<T> eventObject = (Event<T>) event;

        try {
            action(eventObject);
        } catch (final Exception e) {
            LOGGER.log(Level.WARN, "Event perform failed", e);
        } finally { // remove event from event queue
            if (eventQueue instanceof SynchronizedEventQueue) {
                final SynchronizedEventQueue synchronizedEventQueue = (SynchronizedEventQueue) eventQueue;

                synchronizedEventQueue.removeEvent(eventObject);
            }
        }
    }
1205208
def process_task(self):
        """"""
        if _debug: ServerSSM._debug("process_task")

        if self.state == SEGMENTED_REQUEST:
            self.segmented_request_timeout()
        elif self.state == AWAIT_RESPONSE:
            self.await_response_timeout()
        elif self.state == SEGMENTED_RESPONSE:
            self.segmented_response_timeout()
        elif self.state == COMPLETED:
            pass
        elif self.state == ABORTED:
            pass
        else:
            if _debug: ServerSSM._debug("invalid state")
            raise RuntimeError("invalid state")
1207073
function processQueue(){
      try {
        // mark queue as processing to avoid concurrency
        processing = true;

        // process queue
        var item;
        while (item = queue.shift())
          item.fn.call(item.context);
      } finally {
        // queue is not processing anymore
        processing = false;

        // if any function in queue than exception was occured,
        // run rest functions in next code frame
        if (queue.length)
          timer = setImmediate(process);
      }
    }
1263387
def run(self) -> None:
        
        from sslyze.concurrent_scanner import PluginRaisedExceptionScanResult

        # Start processing task in the priority queue first
        current_queue_in = self.priority_queue_in
        while True:

            task = current_queue_in.get()  # Grab a task from queue_in
            if task is None:  # All tasks have been completed
                current_queue_in.task_done()

                if current_queue_in == self.priority_queue_in:
                    # All high priority tasks have been completed; switch to low priority tasks
                    current_queue_in = self.queue_in
                    continue
                else:
                    # All the tasks have been completed; pass on the sentinel to result_queue and exit
                    self.queue_out.put(None)
                    break

            server_info, scan_command = task
            try:
                result = self._synchronous_scanner.run_scan_command(server_info, scan_command)
            except Exception as e:
                # raise
                result = PluginRaisedExceptionScanResult(server_info, scan_command, e)

            # Send the result to queue_out
            self.queue_out.put(result)
            current_queue_in.task_done()
706134
public void complete() {
        long seqNo = this.operation.getSequenceNumber();
        Preconditions.checkState(seqNo >= 0, "About to complete a CompletableOperation that has no sequence number.");

        this.done = true;
        if (this.successHandler != null) {
            Callbacks.invokeSafely(this.successHandler, null, cex -> log.error("Success Callback invocation failure.", cex));
        }
    }
623354
def process_actions(actions):
    """"""
    queue = current_app.config['INDEXER_MQ_QUEUE']
    with establish_connection() as c:
        q = queue(c)
        for action in actions:
            q = action(q)
979445
def after_processing(eng, objects):
        """"""
        super(InvenioProcessingFactory, InvenioProcessingFactory)\
            .after_processing(eng, objects)
        if eng.has_completed:
            eng.save(WorkflowStatus.COMPLETED)
        else:
            eng.save(WorkflowStatus.HALTED)
        db.session.commit()
1279873
protected void processQueue() {
        try {
            Collection<RequestMetric> batch = new ArrayList<>(this.batchSize);
            RequestMetric rm = queue.take();
            batch.add(rm);
			queue.drainTo(batch, this.batchSize - 1);
			
			Builder builder = new Bulk.Builder();
			for (RequestMetric metric : batch) {
	            Index index = new Index.Builder(metric).refresh(false)
	                    .index(getIndexName())
	                    .type("request").build(); //$NON-NLS-1$
				builder.addAction(index);
			}
            
            BulkResult result = getClient().execute(builder.build());
            if (!result.isSucceeded()) {
                logger.warn("Failed to add metric(s) to ES"); //$NON-NLS-1$
            }
        } catch (Exception e) {
            logger.warn("Error adding metric to ES"); //$NON-NLS-1$
            return;
        }
    }
834984
public function process()
    {
        $queue = $this->getQueue();
        $tasks = $this->getTasks();
        foreach ($this->target->getItems() as $targetItem) {
            foreach ($tasks as $task) {
                $action = new QueueAction($this, $this->target, $task[1], $targetItem);
                $queue->send(serialize($action));
            }
        }
    }
605738
private void completeResponses() {
    // Iterate through queued responses and complete as many as possible.
    ResponseCallback response = responseCallbacks.get(responseSequence + 1);
    while (response != null) {
      // If the response was completed, remove the response callback from the response queue,
      // increment the response sequence number, and check the next response.
      if (completeResponse(response.response, response.callback)) {
        responseCallbacks.remove(++responseSequence);
        response = responseCallbacks.get(responseSequence + 1);
      } else {
        break;
      }
    }

    // Once we've completed as many responses as possible, if no more operations are outstanding
    // and events remain in the event queue, complete the events.
    if (requestSequence == responseSequence) {
      EventCallback eventCallback = eventCallbacks.poll();
      while (eventCallback != null) {
        log.trace("Completing {}", eventCallback.request);
        eventCallback.run();
        eventIndex = eventCallback.request.eventIndex();
        eventCallback = eventCallbacks.poll();
      }
    }
  }
440409
private void doProcessNext()
	{
		int _position = getPosition();
		Node _current = getSource().item(_position);

		if (getActionPool().containsKey(_current.getNodeName()))
		{
			getActionPool().get(_current.getNodeName()).execute(_current, _position);
		}
		else if (getActionPool().containsKey(NODE_NAME__DEFAULT))
		{
			getActionPool().get(NODE_NAME__DEFAULT).execute(_current, _position);
		}
		// else do nothing...

		// done
		_position++;
		setPosition(_position);
	}
564214
def _insert_post_complete_tasks(context):
    """"""

    logging.debug("Context %s is complete.", context.id)

    # Async event handlers
    context.exec_event_handler('complete', transactional=True)

    # Insert cleanup tasks
    try:
        # TODO: If tracking results we may not want to auto cleanup and instead
        # wait until the results have been accessed.
        from furious.async import Async
        Async(_cleanup_markers, queue=CLEAN_QUEUE,
              args=[context.id, context.task_ids],
              task_args={'countdown': CLEAN_DELAY}).start()
    except:
        pass
1096630
protected void moveCounter() {
        // Prepare stage, just init
        if (this.stage == 0) {
            this.stage = 1;
            this.counter = -1;
            this.counter2 = 0;
        }
        // First stage. Try to pour every non-empty bucket to every non-full
        if (this.stage == 1) {
            List<PourOperation> sourceBucketOperations;
            // iterating over source buckets
            while (this.counter2 < this.problem.pourOperations.size()) {
                sourceBucketOperations = this.problem.pourOperations.get(this.counter2);

                // source bucket is empty, skip it right away. fetch info from
                // first operation in list
                if (sourceBucketOperations.size() > 0
                        && this.configuration.valueAt(sourceBucketOperations.get(0).sourceBucket.getIndex()) > 0) {
                    // move to next destination bucket
                    this.counter++;
                    while (this.counter < sourceBucketOperations.size()) {
                        // non-full destination
                        if (this.configuration.valueAt(sourceBucketOperations.get(counter).destinationBucket.getIndex())
                                < sourceBucketOperations.get(counter).destinationBucket.getCapacity())
                            return;
                        // try next bucket
                        this.counter++;
                    }
                }
                // depleted all possibilities for this source bucket (or source
                // is empty), move to next source bucket
                this.counter2++;
                this.counter = -1;
            }
            this.stage = 2;
            this.counter = -1;
        }
        // Second stage. Try to spill any non-empty bucket
        if (this.stage == 2) {
            // move to next bucket
            this.counter++;
            while (this.counter < this.problem.getDimension()) {
                // non-empty bucket
                if (this.configuration.valueAt(this.problem.fillOperations.get(counter).bucketItem.getIndex()) > 0)
                    return;
                // try next bucket
                this.counter++;
            }
            // tried all buckets, move to next stage
            this.stage = 3;
            this.counter = -1;
        }
        // Third stage. Try to fill any non-full bucket.
        if (this.stage == 3) {
            // move to next bucket
            this.counter++;
            while (this.counter < this.problem.getDimension()) {
                // non-full bucket
                if (this.configuration.valueAt(this.problem.fillOperations.get(counter).bucketItem.getIndex())
                        < this.problem.buckets.get(counter).getCapacity())
                    return;
                // try next bucket
                this.counter++;
            }
            // tried all buckets, move to next stage
            this.stage = 4;
            this.counter = -1;
        }
    }
1032261
public function process()
    {
        // Run the UpdatePackageInfo task
        $updateTask = Injector::inst()->create(UpdatePackageInfoTask::class);
        $updateTask->run(null);

        // mark job as completed
        $this->isComplete = true;
    }
493550
protected void process(Collection<R> requests) {
        for(;;) {
            while(!requests.isEmpty()) {
                removeAndProcess(requests); // remove matching requests and process them
            }
            lock.lock();
            try {
                if(requests.isEmpty()) {
                    setProcessing(false);
                    return;
                }
            }
            finally {
                lock.unlock();
            }
        }
    }