Performs the task that requires the given list of resources.

<p>
The execution is blocked until the resource is available.

@throws InterruptedException
the thread can be interrupted while waiting for the available resources.
962618
public void execute(@Nonnull Runnable task, final ResourceActivity activity ) throws InterruptedException {
        final ResourceList resources = activity.getResourceList();
        _withLock(new NotReallyRoleSensitiveCallable<Void,InterruptedException>() {
            @Override
            public Void call() throws InterruptedException {
                while (inUse.isCollidingWith(resources)) {
                    // TODO revalidate the resource list after re-acquiring lock, for now we just let the build fail
                    _await();
                }

                // we have a go
                inProgress.add(activity);
                inUse = ResourceList.union(inUse, resources);
                return null;
            }
        });

        try {
            task.run();
        } finally {
           // TODO if AsynchronousExecution, do that later
            _withLock(new Runnable() {
                @Override
                public void run() {
                    inProgress.remove(activity);
                    inUse = ResourceList.union(resourceView);
                    _signalAll();
                }
            });
        }
    }
943165
@Override
	public final T get() throws InterruptedException, ExecutionException {
		block(0);
		if (!isUnblocked()) throw new InterruptedException();
		if (hasError()) throw new ExecutionException(error);
		if (isCancelled()) throw new ExecutionException(cancel);
		return result;
	}
528031
@Override
    public void run() {
        try {
            if (this.isDone()) {
                return;
            }
            ExpeditedFutureTask<V> futureTask = new ExpeditedFutureTask<V>(this.m_callable);
            this.m_defaultFuture = futureTask;
            this.m_executor.execute(futureTask);
            this.m_scheduledExecutorQueue.remove(this);
        } catch (Exception e) {
            this.m_pendingException = new RuntimeException(e);
            return;
        } finally {
            // Let blocked ScheduleFuture methods thru now.
            this.m_coordinationLatch.countDown();
        }
    }
825045
@Override
  public void run() {

    boolean lastAcquireFailed = false;

    while (!halted.get()) {
      try {
        // check if we're supposed to pause...
        synchronized (sigLock) {
          while (paused && !halted.get()) {
            try {
              // wait until togglePause(false) is called...
              sigLock.wait(1000L);
            } catch (InterruptedException ignore) {
            }
          }

          if (halted.get()) {
            break;
          }
        }

        int availThreadCount = quartzSchedulerResources.getThreadPool().blockForAvailableThreads();
        if (availThreadCount
            > 0) { // will always be true, due to semantics of blockForAvailableThreads...

          List<OperableTrigger> triggers = null;

          long now = System.currentTimeMillis();

          clearSignaledSchedulingChange();
          try {
            triggers =
                quartzSchedulerResources
                    .getJobStore()
                    .acquireNextTriggers(
                        now + idleWaitTime,
                        Math.min(availThreadCount, quartzSchedulerResources.getMaxBatchSize()),
                        quartzSchedulerResources.getBatchTimeWindow());
            lastAcquireFailed = false;
            logger.debug(
                "batch acquisition of " + (triggers == null ? 0 : triggers.size()) + " triggers");
          } catch (JobPersistenceException jpe) {

            lastAcquireFailed = true;
          } catch (RuntimeException e) {
            if (!lastAcquireFailed) {
              logger.error("quartzSchedulerThreadLoop: RuntimeException " + e.getMessage(), e);
            }
            lastAcquireFailed = true;
          }

          if (triggers != null && !triggers.isEmpty()) {

            now = System.currentTimeMillis();
            long triggerTime = triggers.get(0).getNextFireTime().getTime();
            long timeUntilTrigger = triggerTime - now;
            while (timeUntilTrigger > 2) {
              synchronized (sigLock) {
                if (halted.get()) {
                  break;
                }
                if (!isCandidateNewTimeEarlierWithinReason(triggerTime, false)) {
                  try {
                    // we could have blocked a long while
                    // on 'synchronize', so we must recompute
                    now = System.currentTimeMillis();
                    timeUntilTrigger = triggerTime - now;
                    if (timeUntilTrigger >= 1) {
                      sigLock.wait(timeUntilTrigger);
                    }
                  } catch (InterruptedException ignore) {
                  }
                }
              }
              if (releaseIfScheduleChangedSignificantly(triggers, triggerTime)) {
                break;
              }
              now = System.currentTimeMillis();
              timeUntilTrigger = triggerTime - now;
            }

            // this happens if releaseIfScheduleChangedSignificantly decided to release triggers
            if (triggers.isEmpty()) {
              continue;
            }

            // set triggers to 'executing'
            List<TriggerFiredResult> bndles = new ArrayList<TriggerFiredResult>();

            boolean goAhead = true;
            synchronized (sigLock) {
              goAhead = !halted.get();
            }
            if (goAhead) {
              try {
                List<TriggerFiredResult> res =
                    quartzSchedulerResources.getJobStore().triggersFired(triggers);
                if (res != null) {
                  bndles = res;
                }
              } catch (SchedulerException se) {
                quartzScheduler.notifySchedulerListenersError(
                    "An error occurred while firing triggers '" + triggers + "'", se);
              }
            }

            for (int i = 0; i < bndles.size(); i++) {

              TriggerFiredResult result = bndles.get(i);
              TriggerFiredBundle bndle = result.getTriggerFiredBundle();
              Exception exception = result.getException();

              if (exception instanceof RuntimeException) {
                logger.error("RuntimeException while firing trigger " + triggers.get(i), exception);

                continue;
              }

              // it's possible to get 'null' if the triggers was paused,
              // blocked, or other similar occurrences that prevent it being
              // fired at this time... or if the scheduler was shutdown (halted)
              if (bndle == null) {
                try {
                  quartzSchedulerResources.getJobStore().releaseAcquiredTrigger(triggers.get(i));
                } catch (SchedulerException se) {
                  quartzScheduler.notifySchedulerListenersError(
                      "An error occurred while releasing triggers '"
                          + triggers.get(i).getName()
                          + "'",
                      se);
                }
                continue;
              }

              // TODO: improvements:
              //
              // 2- make sure we can get a job runshell before firing triggers, or
              // don't let that throw an exception (right now it never does,
              // but the signature says it can).
              // 3- acquire more triggers at a time (based on num threads available?)

              JobRunShell shell = null;
              try {
                shell = quartzSchedulerResources.getJobRunShellFactory().createJobRunShell(bndle);
                shell.initialize(quartzScheduler);
              } catch (SchedulerException se) {
                try {
                  quartzSchedulerResources
                      .getJobStore()
                      .triggeredJobComplete(
                          triggers.get(i),
                          bndle.getJobDetail(),
                          CompletedExecutionInstruction.SET_ALL_JOB_TRIGGERS_ERROR);
                } catch (SchedulerException se2) {
                  quartzScheduler.notifySchedulerListenersError(
                      "An error occurred while placing job's triggers in error state '"
                          + triggers.get(i).getName()
                          + "'",
                      se2);
                }
                continue;
              }

              if (quartzSchedulerResources.getThreadPool().runInThread(shell) == false) {
                try {
                  // this case should never happen, as it is indicative of the
                  // scheduler being shutdown or a bug in the thread pool or
                  // a thread pool being used concurrently - which the docs
                  // say not to do...
                  logger.error("ThreadPool.runInThread() return false!");
                  quartzSchedulerResources
                      .getJobStore()
                      .triggeredJobComplete(
                          triggers.get(i),
                          bndle.getJobDetail(),
                          CompletedExecutionInstruction.SET_ALL_JOB_TRIGGERS_ERROR);
                } catch (SchedulerException se2) {
                  quartzScheduler.notifySchedulerListenersError(
                      "An error occurred while placing job's triggers in error state '"
                          + triggers.get(i).getName()
                          + "'",
                      se2);
                }
              }
            }

            continue; // while (!halted)
          }
        } else { // if(availThreadCount > 0)
          // should never happen, if threadPool.blockForAvailableThreads() follows contract
          continue; // while (!halted)
        }

        long now = System.currentTimeMillis();
        long waitTime = now + getRandomizedIdleWaitTime();
        long timeUntilContinue = waitTime - now;
        synchronized (sigLock) {
          try {
            sigLock.wait(timeUntilContinue);
          } catch (InterruptedException ignore) {
          }
        }

      } catch (RuntimeException re) {
        logger.error("Runtime error occurred in main trigger firing loop.", re);
      }
    } // while (!halted)

    // drop references to scheduler stuff to aid garbage collection...
    quartzScheduler = null;
    quartzSchedulerResources = null;
  }
1143966
public void run()
   {
      this.currentThread = Thread.currentThread();
      this.running.set(true);

      while (this.running.get())
      {
         Task nextTask = null;
         try
         {
            if (_logger.isDebugEnabled())
               _logger.debug("Waiting for next task...");
            nextTask = this.taskSet.take();
            if (_logger.isDebugEnabled())
               _logger.debug("next from taskset is task: " + nextTask.getCommand());
            this.executor.submit(nextTask);
            if (_logger.isDebugEnabled())
               _logger.debug("submitted for execution command: " + nextTask.getCommand());
         }
         catch (InterruptedException e)
         {
            _logger.debug("Task manager thread interrupted.");
            this.running.set(false);
         }
         catch (Exception e)
         {
            _logger.debug("Task manager experienced an unhandled exception, shutting down");
            this.running.set(false);
         }
      }
      _logger.info("Shutting down task manager.");

      this.taskSet.clear();
      executor.shutdown();
   }
371779
private void runTasks() {
        //don't run anything in the IO thread till the tasks are done
        delegate.getSinkChannel().suspendWrites();
        delegate.getSourceChannel().suspendReads();
        List<Runnable> tasks = new ArrayList<>();
        Runnable t = engine.getDelegatedTask();
        while (t != null) {
            tasks.add(t);
            t = engine.getDelegatedTask();
        }

        synchronized (this) {
            outstandingTasks += tasks.size();
            for (final Runnable task : tasks) {
                getWorker().execute(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            task.run();
                        } finally {
                            synchronized (SslConduit.this) {
                                if (outstandingTasks == 1) {
                                    getWriteThread().execute(new Runnable() {
                                        @Override
                                        public void run() {
                                            synchronized (SslConduit.this) {
                                                SslConduit.this.notifyAll();

                                                --outstandingTasks;
                                                try {
                                                    doHandshake();
                                                } catch (IOException | RuntimeException | Error e) {
                                                    IoUtils.safeClose(connection);
                                                }
                                                if (anyAreSet(state, FLAG_READS_RESUMED)) {
                                                    wakeupReads(); //wakeup, because we need to run an unwrap even if there is no data to be read
                                                }
                                                if (anyAreSet(state, FLAG_WRITES_RESUMED)) {
                                                    resumeWrites(); //we don't need to wakeup, as the channel should be writable
                                                }
                                            }
                                        }
                                    });
                                } else {
                                    outstandingTasks--;
                                }
                            }
                        }

                    }
                });
            }
        }
    }
971345
@Override
    public T take(final WaitStrategy.Takeable<T> t) throws InterruptedException {
        T result;

        while ((result = t.take()) == null) {
            Thread.yield();
        }

        return result;
    }
756002
public void asyncOperationStarted() {
    if (syncThread == Thread.currentThread()) {
      synchronized (entry) {
        while (entry.isProcessing()) {
          try {
            entry.wait();
          } catch (InterruptedException ex) {
            Thread.currentThread().interrupt();
          }
        }
      }
    } else {
      entryLocked = false;
    }
  }
22709
public synchronized void execute( AsyncTask task ) throws JMSException
	{		
		AsyncTaskProcessorThread thread = threadPool.borrow(); // Dispatch using new borrowed thread
		if (thread != null)
		{
			thread.setTask(task);
			thread.execute();
		}
		else
		{
			// All threads are busy ...
			
			if (task.isMergeable())
			{
				if (!taskSet.add(task))
					return; // Already queued
			}
			
			// Enqueue task
			taskQueue.add(task);
		}
	}
737391
public void openBlockingInterruptable()
                throws InterruptedException {
            // We need to thread this call in order to interrupt it (when Ctrl-C occurs).
            connectionThread = new Thread(() -> {
                // This thread can't be interrupted from another thread.
                // Will stay alive until System.exit is called.
                Thread thr = new Thread(() -> super.openBlocking(),
                        "CLI Terminal Connection (uninterruptable)");
                thr.start();
                try {
                    thr.join();
                } catch (InterruptedException ex) {
                    // XXX OK, interrupted, just leaving.
                }
            }, "CLI Terminal Connection (interruptable)");
            connectionThread.start();
            connectionThread.join();
        }
1106029
public void setResources(java.util.Collection<Resource> resources) {
        if (resources == null) {
            this.resources = null;
            return;
        }

        this.resources = new java.util.ArrayList<Resource>(resources);
    }
50706
public Page<MonitoredResourceDescriptor> listMonitoredResourceDescriptorsAsync()
      throws ExecutionException, InterruptedException {
    // [START listMonitoredResourceDescriptorsAsync]
    Future<AsyncPage<MonitoredResourceDescriptor>> future =
        logging.listMonitoredResourceDescriptorsAsync(ListOption.pageSize(100));
    // ...
    AsyncPage<MonitoredResourceDescriptor> descriptors = future.get();
    for (MonitoredResourceDescriptor descriptor : descriptors.iterateAll()) {
      // do something with the descriptor
    }
    // [END listMonitoredResourceDescriptorsAsync]
    return descriptors;
  }
426760
public static void prepare() throws InterruptedException {
		semaphore.acquire();
		if (cacheReference == masterCache) {
			slaveCache.clear();
		} else {
			masterCache.clear();
		}
	}
151745
public void onFailure() throws InterruptedException {
        int val = currentFailureCount.incrementAndGet();
        if (val > 50) {
            currentFailureCount.compareAndSet(val, MAX_FAILURE_COUNT);
            val = MAX_FAILURE_COUNT;
        }

        int delay = MIN_DELAY + ((MAX_DELAY - MIN_DELAY) / MAX_FAILURE_COUNT) * val;

        synchronized (this) {
            Logger.d(TAG, "onFailure: wait " + delay + " ms");
            wait(delay);
        }
    }
65558
public static void waitOneFinished(List<? extends Task<?,?>> tasks) {
		if (tasks.isEmpty()) return;
		if (tasks.size() == 1)
			try { tasks.get(0).getOutput().block(0); }
			catch (Throwable e) { /* ignore */ }
		SynchronizationPoint<Exception> sp = new SynchronizationPoint<>();
		for (Task<?,?> t : tasks) {
			if (t.isDone()) return;
			t.getOutput().synchWithNoError(sp);
		}
		sp.block(0);
	}
82489
public void shutdownTasks()
      throws InterruptedException {
    log.info("Shutting down tasks");
    for (Task task: this.tasks) {
      task.shutdown();
    }

    for (Task task : this.tasks) {
      task.awaitShutdown(1000);
    }

    for (Task task : this.tasks) {
      if (task.cancel()) {
        log.info("Task {} cancelled.", task.getTaskId());
      } else {
        log.info("Task {} could not be cancelled.", task.getTaskId());
      }
    }
  }
412300
@Override
    public V poll(long timeout, TimeUnit unit) throws InterruptedException {
        return blockingQueue.poll(timeout, unit);
    }