Start worker threads with a shared log.

@param executorService
the executor service
@param numTasks
the number of worker tasks to start
519106
private void startWorkers(final ExecutorService executorService, final int numTasks) {
        for (int i = 0; i < numTasks; i++) {
            workerFutures.add(executorService.submit(new Callable<Void>() {
                @Override
                public Void call() throws Exception {
                    runWorkLoop();
                    return null;
                }
            }));
        }
    }
1164943
@PostConstruct
    public void start() throws Exception {
        lifecycleLock.writeLock().lock();
        try {
            if (!State.STOPPED.equals(state)) {
                logger.warn("Ignore start() command for {} instance", state);
                return;
            }
            logger.info("Start...");

            for (Query query : queries) {
                query.start();
            }
            for (OutputWriter outputWriter : outputWriters) {
                outputWriter.start();
            }

            collectScheduledExecutor = Executors.newScheduledThreadPool(getNumQueryThreads(), new NamedThreadFactory("jmxtrans-collect-", true));
            exportScheduledExecutor = Executors.newScheduledThreadPool(getNumExportThreads(), new NamedThreadFactory("jmxtrans-export-", true));

            logger.info("Start queries and output writers...");
            for (final Query query : getQueries()) {
                collectScheduledExecutor.scheduleWithFixedDelay(new Runnable() {
                    @Override
                    public void run() {
                        lifecycleLock.readLock().lock();
                        try {
                            if (!State.STARTED.equals(state)) {
                                logger.debug("Ignore query.collectMetrics() command for {} instance", state);
                                return;
                            }
                            query.collectMetrics();
                        } finally {
                            lifecycleLock.readLock().unlock();
                        }
                    }

                    @Override
                    public String toString() {
                        return "Collector[" + query + "]";
                    }
                }, 0, getQueryIntervalInSeconds(), TimeUnit.SECONDS);

                // start export just after first collect
                exportScheduledExecutor.scheduleWithFixedDelay(new Runnable() {
                    @Override
                    public void run() {
                        lifecycleLock.readLock().lock();
                        try {
                            if (!State.STARTED.equals(state)) {
                                logger.debug("Ignore query.exportCollectedMetrics() command for {} instance", state);
                                return;
                            }

                            query.exportCollectedMetrics();
                        } finally {
                            lifecycleLock.readLock().unlock();
                        }
                    }

                    @Override
                    public String toString() {
                        return "Exporter[" + query + "]";
                    }
                }, getQueryIntervalInSeconds() + 1, getExportIntervalInSeconds(), TimeUnit.SECONDS);
            }

            shutdownHook = new EmbeddedJmxTransShutdownHook();
            shutdownHook.registerToRuntime();
            state = State.STARTED;
            logger.info("EmbeddedJmxTrans started");
        } catch (RuntimeException e) {
            this.state = State.ERROR;
            if (logger.isDebugEnabled()) {
                // to troubleshoot JMX call errors or equivalent, it may be useful to log and rethrow
                logger.warn("Exception starting EmbeddedJmxTrans", e);
            }
            throw e;
        } finally {
            lifecycleLock.writeLock().unlock();
        }
    }
148699
synchronized void start(long initialDelay, long period, TimeUnit unit, Runnable runnable) {
        if (this.scheduledFuture != null) {
            throw new IllegalArgumentException("Reporter already started");
        }

        this.scheduledFuture = executor.scheduleAtFixedRate(runnable, initialDelay, period, unit);
    }
1159953
public void start() throws Exception
    {
        Preconditions.checkState(state.compareAndSet(State.LATENT, State.STARTED), "Cannot be started more than once");

        task = executor.scheduleWithFixedDelay
        (
            new Runnable()
            {
                @Override
                public void run()
                {
                    doWork();
                }
            },
            reapingThresholdMs,
            reapingThresholdMs,
            TimeUnit.MILLISECONDS
        );
        if (leaderLatch != null)
        {
            leaderLatch.start();
        }
        reaper.start();
    }
482163
def start_parallel(self):
        
        for _ in range(self.num_threads):
            Worker(self.tasks_queue, self.results_queue, self.exceptions_queue)
1233854
public synchronized void start() {
    if (!_started.get()) {
      _executorService = new ScheduledThreadPoolExecutor(1,
          ExecutorsUtils.newThreadFactory(Optional.of(LoggerFactory.getLogger(FineGrainedWatermarkTracker.class))));
      _executorService.scheduleAtFixedRate(_sweeper, 0, _sweepIntervalMillis, TimeUnit.MILLISECONDS);
      _executorService.scheduleAtFixedRate(_stabilityChecker, 0, _stabilityCheckIntervalMillis, TimeUnit.MILLISECONDS);
    }
    _started.set(true);
  }
173438
private void createAndExecuteTasks(Executor executor, ProcedureFactory<BT> procedureFactory, T[] array)
    {
        this.procedures = new ArrayProcedureFJTask[this.taskCount];
        int sectionSize = array.length / this.taskCount;
        int size = this.taskCount;
        for (int index = 0; index < size; index++)
        {
            ArrayProcedureFJTask<T, BT> procedureFJTask = new ArrayProcedureFJTask<T, BT>(this, procedureFactory, array, index,
                    sectionSize, index == this.taskCount - 1);
            this.procedures[index] = procedureFJTask;
            executor.execute(procedureFJTask);
        }
    }
537548
@Override public void start(Set<File> files, Consumer<Set<File>> callback) {
        if (isStarted()) {
            throw new IllegalStateException("start() should not be called more than once");
        }
        Set<File> filesCopy = ImmutableSet.copyOf(files);
        Preconditions.checkArgument(filesCopy.size() > 0, "must specify at least 1 file to watch for changes");
        this.callback = requireNonNull(callback);
        watchedFiles = filesCopy;
        executorService = MoreExecutors.listeningDecorator(Executors.newScheduledThreadPool(1));
        future = executorService.scheduleAtFixedRate(
            this::scanFilesForChanges,
            initialDelay,
            interval,
            timeUnit);
    }
656786
protected void initializeExecutorServices() {
        final int downloadPoolSize;
        final int max = settings.getInt(Settings.KEYS.MAX_DOWNLOAD_THREAD_POOL_SIZE, 3);
        if (DOWNLOAD_THREAD_POOL_SIZE > max) {
            downloadPoolSize = max;
        } else {
            downloadPoolSize = DOWNLOAD_THREAD_POOL_SIZE;
        }
        downloadExecutorService = Executors.newFixedThreadPool(downloadPoolSize);
        processingExecutorService = Executors.newFixedThreadPool(PROCESSING_THREAD_POOL_SIZE);
        LOGGER.debug("#download   threads: {}", downloadPoolSize);
        LOGGER.debug("#processing threads: {}", PROCESSING_THREAD_POOL_SIZE);
    }
376797
public void startNewThread(Runnable runnable) throws InterruptedException {
        if (TraceComponent.isAnyTracingEnabled()
            && tc.isEntryEnabled())
            SibTr.entry(tc, "startNewThread");

        if (_consumerThreadPool == null) {
            createConsumerThreadPool();
        }
        try {
            _consumerThreadPool.execute(runnable,
                                        ThreadPool.EXPAND_WHEN_QUEUE_IS_FULL_WAIT_AT_LIMIT);
        } catch (ThreadPoolQueueIsFullException e) {
            // Exception should never occur as we are waiting when the queue is
            // full.
            FFDCFilter
                            .processException(
                                              e,
                                              "com.ibm.ws.sib.processor.impl.MessageProcessor.startNewThread",
                                              "1:2705:1.445", this);
        }

        if (TraceComponent.isAnyTracingEnabled()
            && tc.isEntryEnabled())
            SibTr.exit(tc, "startNewThread");
    }
191578
@VisibleForTesting
  protected void startExecutor(final int container, Set<PackingPlan.InstancePlan> instances) {
    LOG.info("Starting a new executor for container: " + container);

    // create a process with the executor command and topology working directory
    final Process containerExecutor = startExecutorProcess(container, instances);

    // associate the process and its container id
    processToContainer.put(containerExecutor, container);
    LOG.info("Started the executor for container: " + container);

    // add the container for monitoring
    startExecutorMonitor(container, containerExecutor, instances);
  }
957724
@Override
  public void start() throws Exception {
    SynchronousQueue<Runnable> synchronousQueue = new SynchronousQueue<>();
    mThreadPool =
        new ThreadPoolExecutor(mMinNumberOfThreads, mMaxNumberOfThreads,
            THREAD_KEEP_ALIVE_TIME_MS, TimeUnit.MILLISECONDS, synchronousQueue);
    mStopped = false;
    try {
      mServerSocket = new ServerSocket(mPort);
    } catch (IOException e) {
      throw new RuntimeException("Failed to bind to port {}.", e);
    }
    while (!mStopped) {
      Socket client;
      try {
        client = mServerSocket.accept();
      } catch (IOException e) {
        if (mServerSocket.isClosed()) {
          break;
        } else {
          continue;
        }
      }
      String clientAddress = client.getInetAddress().getHostAddress();
      LOG.info("Starting thread to read logs from {}", clientAddress);
      AlluxioLog4jSocketNode clientSocketNode = new AlluxioLog4jSocketNode(mBaseLogsDir, client);
      synchronized (mClientSockets) {
        mClientSockets.add(client);
      }
      try {
        CompletableFuture.runAsync(clientSocketNode, mThreadPool)
            .whenComplete((r, e) -> {
              synchronized (mClientSockets) {
                mClientSockets.remove(client);
              }
            });
      } catch (RejectedExecutionException e) {
        // Alluxio log clients (master, secondary master, proxy and workers) establish
        // long-living connections with the log server. Therefore, if the log server cannot
        // find a thread to service a log client, it is very likely due to low number of
        // worker threads. If retry fails, then it makes sense just to let system throw
        // an exception. The system admin should increase the thread pool size.
        String errorMessage = String.format(
            "Log server cannot find a worker thread to service log requests from %s. Increase"
                + " the number of worker threads in the thread pool by configuring"
                + " alluxio.logserver.threads.max in alluxio-site.properties. Current value"
                + " is %d.", clientAddress, mMaxNumberOfThreads);
        throw new RuntimeException(errorMessage, e);
      }
    }
  }
591034
@Override
	public void start() throws Exception {
		synchronized (lock) {
			if (jobExecutorService == null) {
				// create the embedded runtime
				jobExecutorServiceConfiguration = createConfiguration();

				// start it up
				jobExecutorService = createJobExecutorService(jobExecutorServiceConfiguration);
			} else {
				throw new IllegalStateException("The local executor was already started.");
			}
		}
	}
1370675
void start( ScheduledExecutorService service ) {
        if (rollupFuture.get() != null) {
            // already started ...
            return;
        }

        // Pre-populate the metrics (overwriting any existing history object) ...
        durations.put(DurationMetric.QUERY_EXECUTION_TIME, new DurationHistory(TimeUnit.MILLISECONDS,
                                                                               MAXIMUM_LONG_RUNNING_QUERY_COUNT));
        durations.put(DurationMetric.SEQUENCER_EXECUTION_TIME, new DurationHistory(TimeUnit.MILLISECONDS,
                                                                                   MAXIMUM_LONG_RUNNING_SEQUENCING_COUNT));
        durations.put(DurationMetric.SESSION_LIFETIME, new DurationHistory(TimeUnit.MILLISECONDS,
                                                                           MAXIMUM_LONG_RUNNING_SESSION_COUNT));

        for (ValueMetric metric : EnumSet.allOf(ValueMetric.class)) {
            boolean resetUponRollup = !metric.isContinuous();
            values.put(metric, new ValueHistory(resetUponRollup));
        }

        // Initialize the start times in a threadsafe manner ...
        DateTime now = timeFactory.create();
        this.weeksStartTime.compareAndSet(null, now);
        this.daysStartTime.compareAndSet(null, now);
        this.hoursStartTime.compareAndSet(null, now);
        this.minutesStartTime.compareAndSet(null, now);
        this.secondsStartTime.compareAndSet(null, now);
        rollup();

        // Then schedule the rollup to be done at a fixed rate ...
        this.rollupFuture.set(service.scheduleAtFixedRate(new Runnable() {
            @SuppressWarnings( "synthetic-access" )
            @Override
            public void run() {
                rollup();
            }
        }, CAPTURE_DELAY_IN_SECONDS, CAPTURE_INTERVAL_IN_SECONDS, TimeUnit.SECONDS));
    }
689614
public void setExecutorService(ExecutorService v)
   {
      if (v != null)
      {
         executorService = v;
         isExternal = true;
      }
      else
      {
         executorService = null;
         isExternal = false;
      }
   }
550464
@Override
    protected void doStart() {
        log.info("{}: Starting.", this.traceObjectId);

        Services.startAsync(this.durableLog, this.executor)
                .thenComposeAsync(v -> startWhenDurableLogOnline(), this.executor)
                .whenComplete((v, ex) -> {
                    if (ex == null) {
                        // We are started and ready to accept requests when DurableLog starts. All other (secondary) services
                        // are not required for accepting new operations and can still start in the background.
                        notifyStarted();
                    } else {
                        doStop(ex);
                    }
                });
    }
327800
public void run(Collection<Runnable> tasks) {
        // Create a semphore that the wrapped runnables will execute
        int numTasks = tasks.size();
        CountDownLatch latch = new CountDownLatch(numTasks);
        for (Runnable r : tasks) {
            if (r == null)
                throw new NullPointerException("Cannot run null tasks");
            workQueue.offer(new CountingRunnable(r, latch));
        }
        try {
            // Wait until all the tasks have finished
            latch.await();
        }
        catch (InterruptedException ie) {
            throw new IllegalStateException("Not all tasks finished", ie);
        }
    }