Returns a listener that completes when the minimum number of workers for the cluster has been met.
Note: caller should not add a listener using the direct executor, as this can delay the
notifications for other listeners.
177676
public synchronized ListenableFuture<?> waitForMinimumWorkers()
    {
        if (currentCount >= executionMinCount) {
            return immediateFuture(null);
        }

        SettableFuture<?> future = SettableFuture.create();
        futures.add(future);

        // if future does not finish in wait period, complete with an exception
        ScheduledFuture<?> timeoutTask = executor.schedule(
                () -> {
                    synchronized (this) {
                        future.setException(new PrestoException(
                                GENERIC_INSUFFICIENT_RESOURCES,
                                format("Insufficient active worker nodes. Waited %s for at least %s workers, but only %s workers are active", executionMaxWait, executionMinCount, currentCount)));
                    }
                },
                executionMaxWait.toMillis(),
                MILLISECONDS);

        // remove future if finished (e.g., canceled, timed out)
        future.addListener(() -> {
            timeoutTask.cancel(true);
            removeFuture(future);
        }, executor);

        return future;
    }
630154
protected void notifyListeners()
   {
      synchronized (listeners)
      {
         Thread notifier = new NotifyThread(listeners.toArray(new BackupJobListener[listeners.size()]), this);
         notifier.start();
      }
   }
1292608
def listener(self):
        ''''''
        channels = ['ql:w:' + self.client.worker_name]
        listener = Listener(self.client.redis, channels)
        thread = threading.Thread(target=self.listen, args=(listener,))
        thread.start()
        try:
            yield
        finally:
            listener.unlisten()
            thread.join()
1310935
def call_from_executor(self, callback, _max_postpone_until=None):
        
        # Append to list of pending callbacks.
        self._calls_from_executor.append(callback)

        # Set Windows event.
        windll.kernel32.SetEvent(self._event)
1064156
function onFinished (msg, listener) {
  if (isFinished(msg) !== false) {
    defer(listener, null, msg)
    return msg
  }

  // attach the listener to the message
  attachListener(msg, listener)

  return msg
}
1326377
private <T extends Rdp4jListener> void notifyListeners(Class<T> listenerType, Notifier<T> notifier)
            throws InterruptedException {
        for (Rdp4jListener listener : listeners) {
            if (isInstanceOf(listener, listenerType)) {
                /*
                 * This cast is correct, since we check if listener
                 * is instance of listenerType.
                 */
                @SuppressWarnings("unchecked")
                T listener2 = (T) listener;
                try {
                    notifier.notify(listener2);
                } catch (InterruptedException e) {
                    throw e;
                } catch (Throwable e) {
                    logErrorMessage(e);
                }
            }
        }
    }
338801
public void notifyTaskStart(TaskExecutor executor) {
		synchronized (listeners) {
			int size = listeners.size();
			for (int i = 0; i < size; i++) {
				TaskListener listenerl = listeners.get(i);
				listenerl.onStart(executor);
			}
		}
	}
248052
protected void notifyListener(final ExecutorService executor,
    final Future<?> future, final GenericCompletionListener listener) {
    executor.submit(new Runnable() {
      @Override
      public void run() {
        try {
          listener.onComplete(future);
        } catch(Throwable t) {
          getLogger().warn(
            "Exception thrown wile executing " + listener.getClass().getName()
              + ".operationComplete()", t);
        }
      }
    });
  }
1363573
@Override
    public void onOnline(Computer c, TaskListener listener) throws IOException, InterruptedException {
        synchronized(this) {
            future.cancel(false);
            future = Timer.get().schedule(MONITOR_UPDATER, 5, TimeUnit.SECONDS);
        }
    }
1030385
private int countTasksShouldPreempt() {
    int tasksToPreempt = 0;
    long now = ClusterManager.clock.getTime();
    for (PoolGroupSchedulable poolGroup : poolGroupManager.getPoolGroups()) {
      for (PoolSchedulable pool : poolGroup.getPools()) {
        if (pool.isStarving(now)) {
          tasksToPreempt +=
            Math.min(pool.getPending(), pool.getShare() - pool.getGranted());
        }
      }
    }
    return tasksToPreempt;
  }
377815
@Deprecated
    protected synchronized void workerDone(Worker w, boolean taskDied) {

        threads_.remove(w);

        if (taskDied) {
            --activeThreads;
            --poolSize_;
        }

        if (poolSize_ == 0 && shutdown_) {
            maximumPoolSize_ = minimumPoolSize_ = 0; // disable new threads
            notifyAll(); // notify awaitTerminationAfterShutdown
        }

        fireThreadDestroyed(poolSize_);
    }
709112
private static <T> ListenableFuture<T> submitAndAddQueueListener(
      ListeningExecutorService executorService, Callable<T> task,
      final BlockingQueue<Future<T>> queue) {
    final ListenableFuture<T> future = executorService.submit(task);
    future.addListener(new Runnable() {
      @Override public void run() {
        queue.add(future);
      }
    }, directExecutor());
    return future;
  }
1101966
private CompletableFuture<Void> listen() {
    CompletableFuture<Void> future = new CompletableFuture<>();
    context.getThreadContext().executor().execute(() -> {
      internalServer.listen(cluster().member().serverAddress(), context::connectServer).whenComplete((internalResult, internalError) -> {
        if (internalError == null) {
          // If the client address is different than the server address, start a separate client server.
          if (clientServer != null) {
            clientServer.listen(cluster().member().clientAddress(), context::connectClient).whenComplete((clientResult, clientError) -> {
              started = true;
              future.complete(null);
            });
          } else {
            started = true;
            future.complete(null);
          }
        } else {
          future.completeExceptionally(internalError);
        }
      });
    });

    return future;
  }
319294
@Override
    public void notificationCreated(RuntimeUpdateManager updateManager, RuntimeUpdateNotification notification) {

        // CONFIG_UPDATES_DELIVERED notification actually indicates that a config update is starting. The update
        // won't be complete until the future we get from the notification is complete.
        if (RuntimeUpdateNotification.CONFIG_UPDATES_DELIVERED.equals(notification.getName())) {

            configFuture = notification.getFuture();
            _futureMonitor.onCompletion(notification.getFuture(), new CompletionListener<Boolean>() {
                @Override
                public void successfulCompletion(Future<Boolean> future, Boolean result) {
                    // We're done with the update. Set the configFuture to null, and submit a dummy task
                    // so that performAction knows it can kick off the executor.
                    configFuture = null;
                    submit();
                }

                @Override
                public void failedCompletion(Future<Boolean> future, Throwable t) {
                    // The update failed, but we still want to process any queued actions. Set the
                    // configFuture to null, and submit a dummy task so that performAction knows
                    // it can kick off the executor.
                    configFuture = null;
                    submit();
                }

                // Submit a dummy job so that performAction() will kick off the executor for the actions queue
                private void submit() {
                    synchronized (actionQueue) {
                        performAction(new Runnable() {

                            @Override
                            public void run() {
                                return;
                            }
                        });
                    }
                }
            });
        }

    }
1326174
private void configureWorkerThreads(@NotNull NetworkListener networkListener) {
        //WorkerThreadIOStrategy is the default anyway.
        //networkListener.getTransport().setIOStrategy(WorkerThreadIOStrategy.getInstance());

        ThreadPoolConfig config = ThreadPoolConfig.defaultConfig(); //makes a copy
        int numThreads = Runtime.getRuntime().availableProcessors() * 2;
        //setting core and max to the same number is important!
        config.setCorePoolSize(numThreads);
        config.setMaxPoolSize(numThreads);
        //a queue limit is optional but recommended
        config.setQueueLimit(1000);
        networkListener.getTransport().setWorkerThreadPoolConfig(config);
    }
203384
public int getWaiting()
    {
        if (!hasWaiters())
            return 0;
        Iterator<RegisteredSignal> iter = queue.iterator();
        int count = 0;
        while (iter.hasNext())
        {
            Signal next = iter.next();
            if (!next.isCancelled())
                count++;
        }
        return count;
    }
1315878
public Listeners<Job<T>> getOrCreateListeners()
   {
      Node node = childNode.getOrCreate("listeners");
      Listeners<Job<T>> listeners = new ListenersImpl<Job<T>>(this, "listeners", childNode, node);
      return listeners;
   }