/* (non-Javadoc)
@see java.util.concurrent.RejectedExecutionHandler#rejectedExecution(java.lang.Runnable, java.util.concurrent.ThreadPoolExecutor)
493504
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
        if (executor.isShutdown()) {
            throw new RejectedExecutionException();
        }
        
        final BlockingQueue<Runnable> poolQueue = executor.getQueue();
        if (LOG.isDebugEnabled()) {
            LOG.debug("Putting Runnable into BlockingQueue(size=" + poolQueue.size() + ") directly and potentially waiting due to executor rejection");
        }
        
        try {
            poolQueue.put(r);
            if (LOG.isDebugEnabled()) {
                LOG.debug("Put Runnable into BlockingQueue(size=" + poolQueue.size() + ") directly due to executor rejection");
            }
        }
        catch (InterruptedException e) {
            throw new RejectedExecutionException("Interrupted while waiting to queue Runnable", e);
        }
    }
832825
@Override
	public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
		int counts = rejectCounts.incrementAndGet();
		if(logger.isWarnEnabled()) {
			int t = counts % 100;
			if (t == 0)
			{
				logger.warn(new StringBuilder().append("Task[Import DB Data to Elasticsearch] rejected  ").append(counts).append(" times.").toString());
			}
		}
//
		try {
			executor.getQueue().put(r);
		} catch (InterruptedException e1) {
			throw new RejectedExecutionException(e1);
		}
	}
663779
public static void unfailable(final @Nonnull ThrowingRunnable runnable) {
    try {
      runnable.run();
    } catch (final Exception exc) {
      Optional
        .ofNullable(Thread.currentThread().getUncaughtExceptionHandler())
        .ifPresent(ueh -> ueh.uncaughtException(Thread.currentThread(), exc));
    }
  }
786334
@FFDCIgnore(Throwable.class)
    @Override
    public T call() throws Exception {
        final boolean trace = TraceComponent.isAnyTracingEnabled();

        if (future.isCancelled()) {
            if (trace && tc.isDebugEnabled())
                Tr.debug(this, tc, "canceled - not running the task");
            return null;
        }

        Result result = resultRef.get(), resultForThisExecution = result;
        Status<T> skipped = null;
        Status<T> status;
        boolean done = false;
        T taskResult = null;
        ArrayList<ThreadContext> contextAppliedToThread = null;
        resultForThisExecution.executionThread = Thread.currentThread();
        try {
            // EE Concurrency 3.2.6.1: All tasks submitted to an executor must not run if task's component is not started.
            // ThreadContextDescriptor.taskStarting covers this requirement for us.
            contextAppliedToThread = threadContextDescriptor.taskStarting();

            // Determine if task should be skipped
            if (trigger != null)
                try {
                    if (trigger.skipRun(lastExecution, new Date(nextExecutionTime)))
                        skipped = new Status<T>(Status.Type.SKIPPED, null, null, false);
                } catch (Throwable x) {
                    // spec requires skip when skipRun fails
                    Tr.error(tc, "CWWKC1103.skip.run.failed", getName(), managedExecSvc.name, x);
                    skipped = new Status<T>(Status.Type.SKIPPED, null, x, false);
                }

            Date nextExecutionDate = null;

            // Run task if it wasn't skipped
            if (skipped == null) {
                // notify listener: taskStarting
                if (listener != null)
                    try {
                        if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled())
                            Tr.event(this, tc, "taskStarting", managedExecSvc, task);
                        listener.taskStarting(future, managedExecSvc, task);
                    } finally {
                        done = result.getStatus().type == Status.Type.CANCELED;
                    }

                // run the task if the listener didn't cancel it
                status = result.getStatus();
                if (status.type == Status.Type.SUBMITTED && result.compareAndSet(status, new Status<T>(Status.Type.STARTED, null, null, false))) {
                    try {
                        if (trigger == null)
                            if (isCallable)
                                taskResult = ((Callable<T>) task).call();
                            else
                                ((Runnable) task).run();
                        else {
                            long startTime = System.currentTimeMillis();

                            if (isCallable)
                                taskResult = ((Callable<T>) task).call();
                            else
                                ((Runnable) task).run();

                            long endTime = System.currentTimeMillis();
                            String identityName = threadContextDescriptor.getExecutionProperties().get(ManagedTask.IDENTITY_NAME);
                            lastExecution = new LastExecutionImpl(identityName, nextExecutionTime, startTime, endTime, taskResult);
                        }
                    } catch (Throwable x) {
                        Tr.error(tc, "CWWKC1101.task.failed", getName(), managedExecSvc.name, x);
                        status = result.getStatus();
                        if (status.type == Status.Type.CANCELED) // include the failure in the result so it will be available to taskDone
                            result.compareAndSet(status, new Status<T>(Status.Type.CANCELED, null, x, true));
                        else if (status.type == Status.Type.STARTED)
                            result.compareAndSet(status, new Status<T>(Status.Type.DONE, null, x, true));
                        result.latch.countDown();
                    }

                    status = result.getStatus();
                    if (status.type == Status.Type.STARTED) {
                        // calculate next execution
                        if (trigger == null)
                            result.compareAndSet(status, new Status<T>(Status.Type.DONE, taskResult, null, fixedDelay == null && fixedRate == null));
                        else {
                            nextExecutionDate = trigger.getNextRunTime(lastExecution, taskScheduledTime);
                            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
                                Tr.debug(this, tc, "getNextRunTime", trigger, lastExecution,
                                         "taskScheduled " + Utils.toString(taskScheduledTime),
                                         "nextRunTime = " + Utils.toString(nextExecutionDate));

                            result.compareAndSet(status, new Status<T>(Status.Type.DONE, taskResult, null, nextExecutionDate == null));
                        }

                        result.latch.countDown();
                    }

                    done = true;

                    if (listener != null)
                        try {
                            if (status.type == Status.Type.CANCELED)
                                try {
                                    CancellationException cancelX = new CancellationException(Tr.formatMessage(tc, "CWWKC1110.task.canceled", getName(), managedExecSvc.name));
                                    if (trace && tc.isEventEnabled())
                                        Tr.event(this, tc, "taskCanceled", managedExecSvc, task, cancelX);
                                    listener.taskAborted(future, managedExecSvc, task, cancelX);
                                } catch (Throwable x) {
                                    Tr.error(tc, "CWWKC1102.listener.failed", getName(), managedExecSvc.name, x);
                                }

                            Throwable failure = result.getStatus().failure;
                            if (trace && tc.isEventEnabled())
                                Tr.event(this, tc, "taskDone", managedExecSvc, task, failure);
                            listener.taskDone(future, managedExecSvc, task, failure);
                        } catch (Throwable x) {
                            Tr.error(tc, "CWWKC1102.listener.failed", getName(), managedExecSvc.name, x);
                        }
                }
            } else {
                // Skip this execution (only possible if using a trigger)
                try {
                    status = result.getStatus();
                    if (status.type == Status.Type.SUBMITTED)
                        result.compareAndSet(status, skipped);

                    // calculate next execution
                    nextExecutionDate = trigger.getNextRunTime(lastExecution, taskScheduledTime);
                    if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
                        Tr.debug(this, tc, "getNextRunTime", trigger, lastExecution,
                                 "taskScheduled " + Utils.toString(taskScheduledTime),
                                 "nextRunTime = " + Utils.toString(nextExecutionDate));

                    // No next execution
                    if (nextExecutionDate == null)
                        result.compareAndSet(skipped, new Status<T>(Status.Type.SKIPPED, null, skipped.failure, true));
                } finally {
                    result.latch.countDown();

                    // notify listener: taskAborted
                    if (listener != null) {
                        if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled())
                            Tr.event(this, tc, "taskAborted(skipped)", managedExecSvc, task);
                        listener.taskAborted(future, managedExecSvc, task, new SkippedException(skipped.failure));
                    }
                }

                // notify listener: taskDone
                if (listener != null) {
                    if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled())
                        Tr.event(this, tc, "taskDone(skipped)", managedExecSvc, task);
                    listener.taskDone(future, managedExecSvc, task, null);
                }
            }

            // Resubmit this task to run at the next scheduled time
            status = result.getStatus();
            if (!status.finalExecutionIsComplete && (status.type == Status.Type.DONE || status.type == Status.Type.SKIPPED)) {
                if (trace && tc.isEventEnabled())
                    Tr.event(this, tc, "DONE-->NONE (reset for next result)");
                resultRef.set(result = new Result());
                done = false;

                // compute the delay and estimate the next execution time
                long delay;
                if (fixedDelay != null) {
                    delay = fixedDelay;
                    nextExecutionTime = System.nanoTime() + unit.toNanos(delay);
                } else if (fixedRate != null) {
                    // Time elapsed from when the task should have started for the first time
                    long nanoTime = System.nanoTime();
                    long elapsed = unit.convert(nanoTime - taskScheduledNanos, TimeUnit.NANOSECONDS) - initialDelay;
                    delay = ((elapsed / fixedRate) + 1) * fixedRate - elapsed;
                    nextExecutionTime = nanoTime + unit.toNanos(delay);
                } else {
                    nextExecutionTime = nextExecutionDate.getTime();
                    delay = nextExecutionTime - System.currentTimeMillis();
                }

                if (delay < 0)
                    delay = 0;

                // notify listener: taskSubmitted
                if (listener != null)
                    try {
                        result.executionThread = Thread.currentThread();
                        if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled())
                            Tr.event(this, tc, "taskSubmitted", managedExecSvc, task);
                        listener.taskSubmitted(future, managedExecSvc, task);
                    } finally {
                        result.executionThread = null;
                    }

                // reschedule the task if the listener didn't cancel it
                status = result.getStatus();
                if (status.type == Status.Type.NONE && result.compareAndSet(status, new Status<T>(Status.Type.SUBMITTED, null, null, false))) {
                    if (trace && tc.isDebugEnabled())
                        Tr.debug(this, tc, "reschedule " + delay + ' ' + unit + " from now");
                    ScheduledFuture<?> scheduledFuture = managedExecSvc.scheduledExecSvc.schedule(this, delay, unit);
                    future.scheduledFutureRef.set(scheduledFuture);
                }
            }
        } catch (Throwable x) {
            // Some cases where this can happen:
            // component that scheduled the task is no longer available
            // listener.taskAborted (for skipped task) fails
            // trigger.getNextRunTime (for reschedule after skip) fails
            // listener.taskStarting fails
            // trigger.getNextRunTime (for reschedule after success) fails
            // taskAborted or taskDone fails
            // Liberty scheduled executor unavailable, or it fails to schedule

            if (contextAppliedToThread == null && x instanceof IllegalStateException && FrameworkState.isStopping()) {
                if (trace && tc.isDebugEnabled())
                    Tr.debug(this, tc, "Task not started due to server shutdown", getName(), x);
            } else
                Tr.error(tc, "CWWKC1101.task.failed", getName(), managedExecSvc.name, x);

            status = result.getStatus();
            if (!status.finalExecutionIsComplete) {
                Status<T> newStatus = status.type == Status.Type.STARTED ? new Status<T>(Status.Type.DONE, null, x, true) : new Status<T>(Status.Type.ABORTED, null, x, true);
                result.compareAndSet(status, newStatus);
            }
            result.latch.countDown();

            if (listener != null && !done)
                try {
                    try {
                        if (skipped == null && status.type != Status.Type.STARTED) {
                            if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled())
                                Tr.event(this, tc, "taskAborted", managedExecSvc);
                            listener.taskAborted(future, managedExecSvc, task, new AbortedException(x));
                        }
                    } finally {
                        if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled())
                            Tr.event(this, tc, "taskDone", managedExecSvc, task, x);
                        listener.taskDone(future, managedExecSvc, task, x);
                    }
                } catch (Throwable t) {
                    // Log message, but otherwise ignore because we want to the original failure to be raised
                    Tr.error(tc, "CWWKC1102.listener.failed", getName(), managedExecSvc.name, x);
                }

            if (x instanceof Exception)
                throw (Exception) x;
            else
                throw (Error) x;
        } finally {
            resultForThisExecution.executionThread = null;
            if (contextAppliedToThread != null)
                threadContextDescriptor.taskStopping(contextAppliedToThread);
        }

        return taskResult;
    }
247688
@Override
    // thanks to
    // http://binkley.blogspot.fr/2009/04/jumping-work-queue-in-executor.html
    // for backward compat to SDK 8 (JDK 5)
    protected <T> RunnableFuture<T> newTaskFor(Runnable runnable, T value) {
        // makes findbugs happy, there must be some @Nullable
        // annotation in JDK..
        if (runnable == null) {
            return null;
        }
        return new PriorityFuture<T>(runnable, ((PriorityRunnable) runnable).getPriority(), value);
    }
104529
@Override
    public CompletableFuture<RootExecutionResultNode> execute(ExecutionContext context, FieldSubSelection fieldSubSelection) {
        return resolveSubSelection(context, fieldSubSelection)
                .thenApply(RootExecutionResultNode::new);
    }
1359148
@Override
    public void execute() throws UpdateExecutionException {
        try {
            sync();
            getMarkLogicClient().sendUpdateQuery(getQueryString(), getBindings(), getIncludeInferred(), getBaseURI());
        }catch(ForbiddenUserException | FailedRequestException e){
            throw new UpdateExecutionException(e);
        } catch (RepositoryException e) {
            throw new UpdateExecutionException(e);
        } catch (MalformedQueryException e) {
            throw new UpdateExecutionException(e);
        } catch (IOException e) {
            throw new UpdateExecutionException(e);
        }
    }
595245
public static void asyncExecute(Runnable runnable) {
		if (runnable != null) {
			try {
				Para.getExecutorService().execute(runnable);
			} catch (RejectedExecutionException ex) {
				logger.warn(ex.getMessage());
				try {
					runnable.run();
				} catch (Exception e) {
					logger.error(null, e);
				}
			}
		}
	}
1244932
@Override
    protected void doExecute() throws Exception {
        final CommandHandler commandHandler = new CommandHandlerImpl(this.getLog());

        checkStageDirectoryExistence();

        checkRuntimeExistence(commandHandler);

        runFunctions(commandHandler);
    }
569147
@Override
    public void afterExecute(Runnable r, Throwable t)
    {
        super.afterExecute(r,t);
        DebuggableThreadPoolExecutor.logExceptionsAfterExecute(r, t);
    }
1254391
public static ThreadPoolExecutor createThreadPoolExecutor(final int queueSize, final String threadName, ThreadFactory threadFactory, final RejectedExecutionHandler policy)
   {
      if (threadFactory == null) {
         threadFactory = new DefaultThreadFactory(threadName, true);
      }

      LinkedBlockingQueue<Runnable> queue = new LinkedBlockingQueue<>(queueSize);
      ThreadPoolExecutor executor = new ThreadPoolExecutor(1 /*core*/, 1 /*max*/, 5 /*keepalive*/, SECONDS, queue, threadFactory, policy);
      executor.allowCoreThreadTimeOut(true);
      return executor;
   }
212036
private void throwResult(final Result result) {
		this.executor.execute(new Runnable() {
			
			@Override
			public void run() {
				QConnectorAsyncImpl.this.listener.resultReceived("", result);
			}
		});
	}
1214078
protected synchronized boolean reject(JoynrException error) {
        if (isSettled()) {
            return false;
        }
        state = State.REJECTED;
        this.error = error;
        notifyListeners();
        return true;
    }
189264
public static void run(final @Nonnull ThrowingRunnable runnable) {
    Objects.requireNonNull(runnable, "runnable must not be null");
    try {
      runnable.run();
    } catch (final RuntimeException exc) {
      throw exc;
    } catch (final Exception exc) {
      throw new RuntimeException(exc);
    }
  }
636562
public static ExecutorService newBlockingFixedThreadPoolExecutor(int nThreads, int queueSize) {
        BlockingQueue<Runnable> blockingQueue = new ArrayBlockingQueue<>(queueSize);
        RejectedExecutionHandler blockingRejectedExecutionHandler = new RejectedExecutionHandler() {
            @Override
            public void rejectedExecution(Runnable task, ThreadPoolExecutor executor) {
                try {
                    executor.getQueue().put(task);
                } catch (InterruptedException e) {
                }
            }

        };

        return new ThreadPoolExecutor(nThreads, nThreads,
                0L, TimeUnit.MILLISECONDS, blockingQueue,
                blockingRejectedExecutionHandler);
    }
1009526
synchronized void error(@NotNull Exception e) {
        if (isFinished) {
            throw new RuntimeException("Promise already completed!");
        }
        if (e == null) {
            throw new RuntimeException("Error can't be null");
        }
        isFinished = true;
        exception = e;
        deliverResult();
    }
1357425
@Override
  protected boolean requestInvoke(FrameBuffer frameBuffer) {
    Runnable invocation = getRunnable(frameBuffer);
    if (invoker != null) {
      try {
        invoker.execute(invocation);
        return true;
      } catch (RejectedExecutionException rx) {
        LOGGER.warn("ExecutorService rejected execution!", rx);
        return false;
      }
    } else {
      // Invoke on the caller's thread
      invocation.run();
      return true;
    }
  }