Helper method to create a background task for running the interactive evolutionary
algorithm.
@return A Swing task that will execute on a background thread and update
the GUI when it is done.
166134
private SwingBackgroundTask<Sudoku> createTask(final String[] puzzle,
                                                   final int populationSize,
                                                   final int eliteCount)
    {
        return new SwingBackgroundTask<Sudoku>()
        {
            @Override
            protected Sudoku performTask()
            {
                Random rng = new MersenneTwisterRNG();
                List<EvolutionaryOperator<Sudoku>> operators = new ArrayList<EvolutionaryOperator<Sudoku>>(2);
                // Cross-over rows between parents (so offspring is x rows from parent1 and
                // y rows from parent2).
                operators.add(new SudokuVerticalCrossover());
                // Mutate the order of cells within individual rows.
                operators.add(new SudokuRowMutation(new PoissonGenerator(2, rng),
                                                    new DiscreteUniformGenerator(1, 8, rng)));

                EvolutionaryOperator<Sudoku> pipeline = new EvolutionPipeline<Sudoku>(operators);

                EvolutionEngine<Sudoku> engine = new GenerationalEvolutionEngine<Sudoku>(new SudokuFactory(puzzle),
                                                                                         pipeline,
                                                                                         new SudokuEvaluator(),
                                                                                         selectionStrategy,
                                                                                         rng);
                engine.addEvolutionObserver(new SwingEvolutionObserver<Sudoku>(new GridViewUpdater(),
                                                                               100,
                                                                               TimeUnit.MILLISECONDS));
                engine.addEvolutionObserver(statusBar);
                return engine.evolve(populationSize,
                                     eliteCount,
                                     new TargetFitness(0, false), // Continue until a perfect solution is found...
                                     abortControl.getTerminationCondition()); // ...or the user aborts.
            }


            @Override
            protected void postProcessing(Sudoku result)
            {
                puzzleCombo.setEnabled(true);
                populationSizeSpinner.setEnabled(true);
                solveButton.setEnabled(true);
                abortControl.getControl().setEnabled(false);
            }
        };
    }
498709
static <T extends IncrementalTask> IncrementalTaskState<T> create(
      String taskId, String jobId, long createTime, T initialTask) {
    return new IncrementalTaskState<>(taskId, jobId, createTime, new LockInfo(null, null),
        checkNotNull(initialTask), new Status(StatusCode.RUNNING));
  }
143546
public synchronized FutureTask<Boolean> start() {
        this.sessionFactory.start();
        if (rpcTimeoutChecker != null) {
            rpcTimeoutChecker.getThread().start();
        }
        final FutureTask<Boolean> futureTask = new FutureTask<Boolean>(
                new Callable<Boolean>() {
                    @Override
                    public Boolean call() throws Exception {
                        while (!ExecutionVenueNioClient.this.sessionFactory.isConnected()) {
                            Thread.sleep(50);
                        }
                        return true;
                    }
                });
        final Thread thread = new Thread(futureTask);
        thread.setDaemon(true);
        thread.start();
        return futureTask;
    }
866018
public <TContinuationResult> Task<TContinuationResult> onSuccessTask(
      final Continuation<TResult, Task<TContinuationResult>> continuation) {
    return onSuccessTask(continuation, IMMEDIATE_EXECUTOR);
  }
275018
@Override
    public Future<?> submit(Runnable task) {
        if (task == null) {
            throw new NullPointerException();
        }
        RunnableFuture<Object> ftask = newTaskFor(task, null);
        execute(ftask);
        return ftask;
    }
1221259
public void execute(Runnable task, long timeoutMillis) throws RejectedExecutionException {
        if (task == null) {
            throw new NullPointerException("Cannot accept null task");
        }
        synchronized (this) {
            if (mState != STATE_RUNNING && mState != STATE_NOT_STARTED) {
                throw new RejectedExecutionException("Task queue is shutdown");
            }
        }
        try {
            if (!mQueue.offer(task, timeoutMillis, TimeUnit.MILLISECONDS)) {
                throw new RejectedExecutionException("Unable to enqueue task after waiting " +
                                                     timeoutMillis + " milliseconds");
            }
        } catch (InterruptedException e) {
            throw new RejectedExecutionException(e);
        }
    }
1191957
public synchronized AbstractCompactionTask getNextBackgroundTask(int gcBefore)
    {
        if (!isEnabled())
            return null;
        Collection<AbstractCompactionTask> tasks = getMaximalTask(gcBefore);
        if (tasks == null || tasks.size() == 0)
            return null;
        return tasks.iterator().next();
    }
198442
public Task poll() {
        Task result = taskList[activeIndex].poll();
        if (result != null) {
            if (activeIndex == 0)
                result.removeFromQueue0();
            else
                result.removeFromQueue1();
        }

        return result;
    }
749262
static ContinuableFuture<Void> executeOnUiThread(final Try.Runnable<? extends Exception> action, final long delay) {
        return execute(new FutureTask<Void>(FN.toCallable(action)), _UI_EXECUTOR, delay);
    }
134869
static ContinuableFuture<Void> executeWithThreadPool(final Try.Runnable<? extends Exception> action) {
        return execute(new FutureTask<Void>(FN.toCallable(action)), TP_EXECUTOR);
    }
836095
protected Runnable wrapTask(Runnable task) {
    // Preserve the MDC context of the caller thread.
    Map contextMap = MDC.getCopyOfContextMap();
    if (contextMap != null) {
      return new MDCRunnableAdapter(task, contextMap);
    }
    return task;
  }
628604
public AnalysisResultFuture run() {
        try {
            // the injection manager is job scoped
            final InjectionManager injectionManager = _configuration.getInjectionManager(_job);

            final LifeCycleHelper rowProcessingLifeCycleHelper = new LifeCycleHelper(injectionManager,
                    new ReferenceDataActivationManager(), _includeNonDistributedTasks);

            final RowProcessingPublishers publishers = new RowProcessingPublishers(_job, _analysisListener,
                    _taskRunner, rowProcessingLifeCycleHelper, _sourceColumnFinder);

            final AnalysisJobMetrics analysisJobMetrics = publishers.getAnalysisJobMetrics();

            // A task listener that will register either succesfull executions
            // or unexpected errors (which will be delegated to the
            // errorListener)
            JobCompletionTaskListener jobCompletionTaskListener = new JobCompletionTaskListener(analysisJobMetrics,
                    _analysisListener, 1);

            _analysisListener.jobBegin(_job, analysisJobMetrics);

            validateSingleTableInput(_transformerJobs);
            validateSingleTableInput(_filterJobs);
            validateSingleTableInput(_analyzerJobs);

            // at this point we are done validating the job, it will run.
            scheduleRowProcessing(publishers, rowProcessingLifeCycleHelper, jobCompletionTaskListener,
                    analysisJobMetrics);

            return new AnalysisResultFutureImpl(_resultQueue, jobCompletionTaskListener, _errorAware);
        } catch (RuntimeException e) {
            _analysisListener.errorUknown(_job, e);
            throw e;
        }

    }
882280
public final Task<T,TError> start() {
		if (this instanceof Done) return this;
		if (cancelling != null) result.cancelled(cancelling);
		synchronized (this) {
			if (result.isCancelled()) return this;
			if (status != Task.STATUS_NOT_STARTED) {
				if (status >= Task.STATUS_DONE)
					throw new RuntimeException("Task already done: " + description
						+ " with " + (result.getError() != null ? "error " + result.getError().getMessage() : "success"));
				throw new RuntimeException("Task already started (" + status + "): " + description);
			}
			// check if waiting for time
			if (nextExecution > 0) {
				long now = System.currentTimeMillis();
				if (nextExecution > now) {
					TaskScheduler.schedule(this);
					return this;
				}
			}
			// ready to be executed
			sendToTaskManager();
			return this;
		}
	}
986533
protected RunnerResult doExecute(Cron4jJob job, TaskExecutionContext context, OptionalThing<LaunchNowOption> nowOption) { // e.g. concurrent control, cross vm
        // ...may be hard to read, synchronized hell
        final String cronExp;
        final VaryingCronOption cronOption;
        debugFw("...Locking varying lock (before run): {}", varyingLock);
        synchronized (varyingLock) {
            cronExp = varyingCron.getCronExp();
            cronOption = varyingCron.getCronOption();
        }
        final List<NeighborConcurrentGroup> neighborConcurrentGroupList = job.getNeighborConcurrentGroupList();
        debugFw("...Locking preparing lock (before run): {}", preparingLock);
        synchronized (preparingLock) { // waiting for previous preparing end
            final OptionalThing<RunnerResult> concurrentResult = stopConcurrentJobIfNeeds(job);
            if (concurrentResult.isPresent()) { // e.g. quit, error
                return concurrentResult.get();
            }
            // no duplicate or duplicate as waiting, here
            final OptionalThing<RunnerResult> neighborConcurrentResult =
                    synchronizedNeighborPreparing(neighborConcurrentGroupList.iterator(), () -> {
                        final OptionalThing<RunnerResult> result = stopNeighborConcurrentJobIfNeeds(job, neighborConcurrentGroupList);
                        if (!result.isPresent()) { // no duplicate neighbor or duplicate as waiting
                            sleepForLockableLife(); // not to get running lock before previous thread in crevasse point
                            debugFw("...Locking running lock (before run): {}", runningLock);
                            synchronized (runningLock) { // waiting for previous running end
                                debugFw("...Locking running state in preparing and running lock (before run): {}", runningState);
                                synchronizedNeighborRunning(neighborConcurrentGroupList.iterator(), () -> { // also neighbor's running
                                    synchronized (runningState) { // to protect running state, begin() and end()
                                        // may be override by crevasse headache, but recover it later
                                        runningState.begin(); // needs to get in preparing lock, to suppress duplicate begin()
                                    }
                                    return null; // unused
                                });
                            }
                        }
                        return result;
                    });
            if (neighborConcurrentResult.isPresent()) { // e.g. quit, error
                return neighborConcurrentResult.get();
            }
        }
        // *here is first crevasse point
        // (really want to get running lock before returning preparing lock)
        debugFw("...Locking running lock (before run): {}", runningLock);
        synchronized (runningLock) { // to make next thread wait for me (or waiting by crevasse headache)
            try { // *here is second crevasse point
                return synchronizedNeighborRunning(neighborConcurrentGroupList.iterator(), () -> {
                    if (!runningState.getBeginTime().isPresent()) { // almost no way, but may be crevasse headache
                        runningState.begin(); // just in case
                    }
                    final OptionalThing<CrossVMState> crossVMState = crossVMBeginning(job);
                    if (crossVMState.isPresent() && crossVMState.get().isQuit()) {
                        return RunnerResult.asQuitByConcurrent(); // quit by cross VM handling
                    }
                    final RunnerResult runnerResult;
                    final LocalDateTime endTime;
                    try {
                        debugFw("...Calling actuallyExecute() of task (before run): {}", job);
                        runnerResult = actuallyExecute(job, cronExp, cronOption, context, nowOption);
                    } finally {
                        debugFw("...Calling finally clause of job execution (after run)");
                        endTime = currentTime.get();
                        crossVMEnding(job, crossVMState, endTime);
                    }
                    runnerResult.acceptEndTime(endTime); // lazy load now
                    return runnerResult;
                });
            } finally {
                debugFw("...Locking running state in running lock (after run): {}", runningState);
                synchronized (runningState) { // running state is only my job so outside neighbor synchronization
                    if (runningState.getBeginTime().isPresent()) {
                        runningState.end(); // for controller dead
                    }
                }
            }
        }
    }
929976
public Task add()
   {
      Task task = new Task(m_projectFile, (Task) null);
      add(task);
      m_projectFile.getChildTasks().add(task);
      return task;
   }
371167
public void doBackgroundOp( final Runnable run, final boolean showWaitCursor )
  {
    final Component[] key = new Component[1];
    ExecutorService jobRunner = getJobRunner();
    if( jobRunner != null )
    {
      jobRunner.submit( () -> performBackgroundOp( run, key, showWaitCursor ) );
    }
    else
    {
      run.run();
    }
  }
1001318
public <TContinuationResult> Task<TContinuationResult> onSuccessTask(
      final Continuation<TResult, Task<TContinuationResult>> continuation, Executor executor) {
    return onSuccessTask(continuation, executor, null);
  }