Registers a new task manager at the slot manager. This will make the task managers slots
known and, thus, available for allocation.

@param taskExecutorConnection for the new task manager
@param initialSlotReport for the new task manager
556903
public void registerTaskManager(final TaskExecutorConnection taskExecutorConnection, SlotReport initialSlotReport) {
		checkInit();

		LOG.debug("Registering TaskManager {} under {} at the SlotManager.", taskExecutorConnection.getResourceID(), taskExecutorConnection.getInstanceID());

		// we identify task managers by their instance id
		if (taskManagerRegistrations.containsKey(taskExecutorConnection.getInstanceID())) {
			reportSlotStatus(taskExecutorConnection.getInstanceID(), initialSlotReport);
		} else {
			// first register the TaskManager
			ArrayList<SlotID> reportedSlots = new ArrayList<>();

			for (SlotStatus slotStatus : initialSlotReport) {
				reportedSlots.add(slotStatus.getSlotID());
			}

			TaskManagerRegistration taskManagerRegistration = new TaskManagerRegistration(
				taskExecutorConnection,
				reportedSlots);

			taskManagerRegistrations.put(taskExecutorConnection.getInstanceID(), taskManagerRegistration);

			// next register the new slots
			for (SlotStatus slotStatus : initialSlotReport) {
				registerSlot(
					slotStatus.getSlotID(),
					slotStatus.getAllocationID(),
					slotStatus.getJobID(),
					slotStatus.getResourceProfile(),
					taskExecutorConnection);
			}
		}

	}
6924
@Override
    public void execute(Runnable task) {
        Executor executor = getScheduledExecutor();
        try {
            executor.execute(errorHandlingTask(task, false));
        } catch (RejectedExecutionException ex) {
            throw new TaskRejectedException("Executor [" + executor + "] did not accept task: " + task, ex);
        }
    }
514486
@Override
  public Map<String, Object> callExecutorStats(final int executorId, final String action,
      final Pair<String, String>... params) throws IOException, ExecutorManagerException {
    final Executor executor = fetchExecutor(executorId);

    final List<Pair<String, String>> paramList =
        new ArrayList<>();

    // if params = null
    if (params != null) {
      paramList.addAll(Arrays.asList(params));
    }

    paramList
        .add(new Pair<>(ConnectorParams.ACTION_PARAM, action));

    return this.apiGateway.callForJsonObjectMap(executor.getHost(), executor.getPort(),
        "/stats", paramList);
  }
1301644
@Override
    public ScheduledFuture<?> scheduleAtFixedRate(Runnable task, Date startTime, long period) {
        long initialDelay = startTime.getTime() - System.currentTimeMillis();
        try {
            return this.scheduledExecutor.scheduleAtFixedRate(decorateTask(task, true), initialDelay, period,
                    TimeUnit.MILLISECONDS);
        } catch (RejectedExecutionException ex) {
            throw new TaskRejectedException("Executor [" + this.scheduledExecutor + "] did not accept task: " + task,
                    ex);
        }
    }
65009
public void start(ExecutorService executorService, Callable<Future<R>> innerTask, ThreadContextDescriptor threadContext) {
        synchronized (this) {
            this.innerTask = innerTask;
            this.threadContext = threadContext;
            //set up the future to hold the result
            this.resultFuture = new CompletableFuture<Future<R>>();
            //submit the innerTask (wrapped by this) for execution
            this.taskFuture = executorService.submit(this);
        }
    }
443092
@SuppressWarnings("RV_RETURN_VALUE_IGNORED_BAD_PRACTICE")
    @JavaScriptMethod public final void start() {
        Ancestor ancestor = Stapler.getCurrentRequest().findAncestor(BoundObjectTable.class);
        if (ancestor == null) {
            throw new IllegalStateException("no BoundObjectTable");
        }
        boundObjectTable = ((BoundObjectTable) ancestor.getObject()).getTable();
        boundId = ancestor.getNextToken(0);
        LOG.log(Level.FINE, "starting rendering {0} at {1}", new Object[] {uri, boundId});
        final ExecutorService executorService = executorService();
        executorService.submit(new Runnable() {
            @Override public void run() {
                lastNewsTime = start = System.currentTimeMillis();
                setCurrentRequest(request);
                SecurityContext orig = SecurityContextHolder.getContext();
                try {
                    SecurityContextHolder.setContext(securityContext);
                    compute();
                    if (status != CANCELED && status != ERROR) {
                        status = 1;
                    }
                } catch (Exception x) {
                    LOG.log(Level.WARNING, "failed to compute " + uri, x);
                    status = ERROR;
                } finally {
                    SecurityContextHolder.setContext(orig);
                    setCurrentRequest(null);
                    LOG.log(Level.FINE, "{0} finished in {1}msec with status {2}", new Object[] {uri, System.currentTimeMillis() - start, status});
                }
                if (executorService instanceof ScheduledExecutorService) {
                    ((ScheduledExecutorService) executorService).schedule(new Runnable() {
                        @Override public void run() {
                            LOG.log(Level.FINE, "some time has elapsed since {0} finished, so releasing", boundId);
                            release();
                        }
                    }, timeout() /* add some grace period for browser/network overhead */ * 2, TimeUnit.MILLISECONDS);
                }
            }
        });
    }
370311
@SuppressWarnings("unchecked")
	private void startScheduler(){

		scheduledExecutorService.scheduleAtFixedRate(new Runnable() {

			@Override
			@SuppressWarnings("rawtypes")
			public void run()  {

				Iterator<Entry<String, Long>> it = transactionCallbackTime.entrySet().iterator();
				while (it.hasNext()) {
					Map.Entry pair = (Map.Entry)it.next();
					if ((System.currentTimeMillis() - (Long)pair.getValue()) > 5000 ){
						final String xferId = (String)pair.getKey();
						it.remove();
						status.put(xferId, "ERROR");
						ascpCount -= numberOfSessionsInTransaction(xferId);
						removeAllTransactionSessions(xferId);
						removeTransactionProgressData(xferId);
						log.error("Status marked as [ERROR] for xferId [" + xferId + "] after not reporting for over 5 seconds");
					}
				}
			}
		},5,5,TimeUnit.SECONDS);
	}
719876
private synchronized void createExecutor() {
        if (componentConfig == null) {
            // this is a completely normal occurrence and can happen if a ThreadFactory is bound prior to
            // component activation...  the proper thing to do is to do nothing and wait for activation
            return;
        }

        if (threadPoolController != null)
            threadPoolController.deactivate();

        ThreadPoolExecutor oldPool = threadPool;

        poolName = (String) componentConfig.get("name");
        String threadGroupName = poolName + " Thread Group";

        int coreThreads = Integer.parseInt(String.valueOf(componentConfig.get("coreThreads")));
        int maxThreads = Integer.parseInt(String.valueOf(componentConfig.get("maxThreads")));

        if (maxThreads <= 0) {
            maxThreads = Integer.MAX_VALUE;
        }

        if (coreThreads < 0) {
            coreThreads = 2 * CpuInfo.getAvailableProcessors();
        }

        // Make sure coreThreads is not bigger than maxThreads, subject to MINIMUM_POOL_SIZE limit
        coreThreads = Math.max(MINIMUM_POOL_SIZE, Math.min(coreThreads, maxThreads));
        // ... and then make sure maxThreads is not smaller than coreThreads ...
        maxThreads = Math.max(coreThreads, maxThreads);

        BlockingQueue<Runnable> workQueue = new BoundedBuffer<Runnable>(java.lang.Runnable.class, 1000, 1000);

        RejectedExecutionHandler rejectedExecutionHandler = new ExpandPolicy(workQueue, this);

        threadPool = new ThreadPoolExecutor(coreThreads, maxThreads, 0, TimeUnit.MILLISECONDS, workQueue, threadFactory != null ? threadFactory : new ThreadFactoryImpl(poolName, threadGroupName), rejectedExecutionHandler);

        threadPoolController = new ThreadPoolController(this, threadPool);

        if (oldPool != null) {
            softShutdown(oldPool);
        }
    }
1241112
private void submitResults(Object task, Object results) throws JobExecutionException {
    synchronized (monitor) {
      this.job.submitTaskResults(task, results, monitor);
    }
  }
195676
void initialize(ScheduledExecutorService executor, String cacheName, Configuration cfg) {
      this.executor = executor;
      this.configuration = cfg;
      this.cacheName = cacheName;
   }
547113
private static void startIfNeeded()
   {
      if (!STARTED)
      {
         synchronized (JCRStatisticsManager.class)
         {
            if (!STARTED)
            {
               addTriggers();
               ExoContainer container = ExoContainerContext.getTopContainer();
               ManagementContext ctx = null;
               if (container != null)
               {
                  ctx = container.getManagementContext();
               }
               if (ctx == null)
               {
                  LOG.warn("Cannot register the statistics");
               }
               else
               {
                  ctx.register(new JCRStatisticsManager());
               }
               STARTED = true;
            }
         }
      }
   }
747050
public void initAsyncExecutor() {
    if (asyncExecutor == null) {
      DefaultAsyncJobExecutor defaultAsyncExecutor = new DefaultAsyncJobExecutor();

      // Message queue mode
      defaultAsyncExecutor.setMessageQueueMode(asyncExecutorMessageQueueMode);

      // Thread pool config
      defaultAsyncExecutor.setCorePoolSize(asyncExecutorCorePoolSize);
      defaultAsyncExecutor.setMaxPoolSize(asyncExecutorMaxPoolSize);
      defaultAsyncExecutor.setKeepAliveTime(asyncExecutorThreadKeepAliveTime);

      // Threadpool queue
      if (asyncExecutorThreadPoolQueue != null) {
        defaultAsyncExecutor.setThreadPoolQueue(asyncExecutorThreadPoolQueue);
      }
      defaultAsyncExecutor.setQueueSize(asyncExecutorThreadPoolQueueSize);

      // Acquisition wait time
      defaultAsyncExecutor.setDefaultTimerJobAcquireWaitTimeInMillis(asyncExecutorDefaultTimerJobAcquireWaitTime);
      defaultAsyncExecutor.setDefaultAsyncJobAcquireWaitTimeInMillis(asyncExecutorDefaultAsyncJobAcquireWaitTime);

      // Queue full wait time
      defaultAsyncExecutor.setDefaultQueueSizeFullWaitTimeInMillis(asyncExecutorDefaultQueueSizeFullWaitTime);

      // Job locking
      defaultAsyncExecutor.setTimerLockTimeInMillis(asyncExecutorTimerLockTimeInMillis);
      defaultAsyncExecutor.setAsyncJobLockTimeInMillis(asyncExecutorAsyncJobLockTimeInMillis);
      if (asyncExecutorLockOwner != null) {
        defaultAsyncExecutor.setLockOwner(asyncExecutorLockOwner);
      }

      // Reset expired
      defaultAsyncExecutor.setResetExpiredJobsInterval(asyncExecutorResetExpiredJobsInterval);
      defaultAsyncExecutor.setResetExpiredJobsPageSize(asyncExecutorResetExpiredJobsPageSize);

      // Shutdown
      defaultAsyncExecutor.setSecondsToWaitOnShutdown(asyncExecutorSecondsToWaitOnShutdown);

      asyncExecutor = defaultAsyncExecutor;
    }

    asyncExecutor.setProcessEngineConfiguration(this);
    asyncExecutor.setAutoActivate(asyncExecutorActivate);
  }
569112
private void executeReactor(final InitStrategy is, TaskBuilder... builders) throws IOException, InterruptedException, ReactorException {
        Reactor reactor = new Reactor(builders) {
            /**
             * Sets the thread name to the task for better diagnostics.
             */
            @Override
            protected void runTask(Task task) throws Exception {
                if (is!=null && is.skipInitTask(task))  return;

                ACL.impersonate(ACL.SYSTEM); // full access in the initialization thread
                String taskName = InitReactorRunner.getDisplayName(task);

                Thread t = Thread.currentThread();
                String name = t.getName();
                if (taskName !=null)
                    t.setName(taskName);
                try {
                    long start = System.currentTimeMillis();
                    super.runTask(task);
                    if(LOG_STARTUP_PERFORMANCE)
                        LOGGER.info(String.format("Took %dms for %s by %s",
                                System.currentTimeMillis()-start, taskName, name));
                } catch (Exception | Error x) {
                    if (containsLinkageError(x)) {
                        LOGGER.log(Level.WARNING, taskName + " failed perhaps due to plugin dependency issues", x);
                    } else {
                        throw x;
                    }
                } finally {
                    t.setName(name);
                    SecurityContextHolder.clearContext();
                }
            }
            private boolean containsLinkageError(Throwable x) {
                if (x instanceof LinkageError) {
                    return true;
                }
                Throwable x2 = x.getCause();
                return x2 != null && containsLinkageError(x2);
            }
        };

        new InitReactorRunner() {
            @Override
            protected void onInitMilestoneAttained(InitMilestone milestone) {
                initLevel = milestone;
                if (milestone==PLUGINS_PREPARED) {
                    // set up Guice to enable injection as early as possible
                    // before this milestone, ExtensionList.ensureLoaded() won't actually try to locate instances
                    ExtensionList.lookup(ExtensionFinder.class).getComponents();
                }
            }
        }.run(reactor);
    }
364363
@Subscribe
  public void onStart(AggregatedStartEvent e) throws IOException {
    this.totalSuites = e.getSuiteCount();
    logShort("Executing " +
        totalSuites + Pluralize.pluralize(totalSuites, " suite") +
        " with " + 
        e.getSlaveCount() + Pluralize.pluralize(e.getSlaveCount(), " JVM") + ".\n", false);

    forkedJvmCount = e.getSlaveCount();
    jvmIdFormat = " J%-" + (1 + (int) Math.floor(Math.log10(forkedJvmCount))) + "d";

    outWriter = new PrefixedWriter(stdoutIndent, output, DEFAULT_MAX_LINE_WIDTH);
    errWriter = new PrefixedWriter(stderrIndent, output, DEFAULT_MAX_LINE_WIDTH);        
  }
606135
void registerTaskStarted(Task task) {
        synchronized (m_activeTasks) {
            String mapKey = createMapKey(task.getTenant(), task.getTaskID());
            if (m_activeTasks.put(mapKey, task) != null) {
                m_logger.warn("Task {} registered as started but was already running", mapKey);
            }
        }
    }
711818
@Override
	public void onStart() throws Exception {
		try {
			startTaskExecutorServices();
		} catch (Exception e) {
			final TaskManagerException exception = new TaskManagerException(String.format("Could not start the TaskExecutor %s", getAddress()), e);
			onFatalError(exception);
			throw exception;
		}

		startRegistrationTimeout();
	}
213512
public void setTaskExecutions(java.util.Collection<TaskExecutionListEntry> taskExecutions) {
        if (taskExecutions == null) {
            this.taskExecutions = null;
            return;
        }

        this.taskExecutions = new java.util.ArrayList<TaskExecutionListEntry>(taskExecutions);
    }