下面列出了java.util.concurrent.AbstractExecutorService#java.util.concurrent.RejectedExecutionException 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
public void endpointNowInUse(Endpoint endpoint) {
int count = endpointCount.incrementAndGet();
if(pool.getLoggerI18n().fineEnabled()) {
pool.getLoggerI18n().fine("InstantiatorRecoveryTask - EndpointNowInUse. Now have " + count + " endpoints");
}
if(count == 1) {
synchronized(recoveryScheduledLock) {
if(!recoveryScheduled) {
try {
recoveryScheduled = true;
background.execute(new RecoveryTask());
pool.getLoggerI18n().fine("InstantiatorRecoveryTask - Scheduled Recovery Task");
} catch(RejectedExecutionException e) {
//ignore, the timer has been cancelled, which means we're shutting down.
}
}
}
}
}
@Override
public Future<?> submit(Runnable task) {
try {
if (this.concurrentExecutor instanceof ExecutorService) {
return ((ExecutorService) this.concurrentExecutor).submit(task);
}
else {
FutureTask<Object> future = new FutureTask<Object>(task, null);
this.concurrentExecutor.execute(future);
return future;
}
}
catch (RejectedExecutionException ex) {
throw new TaskRejectedException(
"Executor [" + this.concurrentExecutor + "] did not accept task: " + task, ex);
}
}
/**
* execute throws RejectedExecutionException if saturated.
*/
public void testSaturatedExecute() {
final CountDownLatch done = new CountDownLatch(1);
final ThreadPoolExecutor p =
new ThreadPoolExecutor(1, 1,
LONG_DELAY_MS, MILLISECONDS,
new ArrayBlockingQueue<Runnable>(1));
try (PoolCleaner cleaner = cleaner(p, done)) {
Runnable task = new CheckedRunnable() {
public void realRun() throws InterruptedException {
await(done);
}};
for (int i = 0; i < 2; ++i)
p.execute(task);
for (int i = 0; i < 2; ++i) {
try {
p.execute(task);
shouldThrow();
} catch (RejectedExecutionException success) {}
assertTrue(p.getTaskCount() <= 2);
}
}
}
@Override
public void received(Channel channel, Object message) throws RemotingException {
ExecutorService cexecutor = getExecutorService();
try {
cexecutor.execute(new ChannelEventRunnable(channel, handler, ChannelState.RECEIVED, message));
} catch (Throwable t) {
//fix, reject exception can not be sent to consumer because thread pool is full, resulting in consumers waiting till timeout. 修复,由于线程池已满,拒绝异常无法发送给使用者,导致使用者等待超时。
if (message instanceof Request && t instanceof RejectedExecutionException) {
Request request = (Request) message;
if (request.isTwoWay()) {
String msg = "Server side(" + url.getIp() + "," + url.getPort() + ") threadpool is exhausted ,detail msg:" + t.getMessage();
Response response = new Response(request.getId(), request.getVersion());
response.setStatus(Response.SERVER_THREADPOOL_EXHAUSTED_ERROR);
response.setErrorMessage(msg);
channel.send(response);
return;
}
}
throw new ExecutionException(message, channel, getClass() + " error when process received event .", t);
}
}
/**
* Initializes or doubles the capacity of array. Call either
* by owner or with lock held -- it is OK for base, but not
* top, to move while resizings are in progress.
*/
final ForkJoinTask<?>[] growArray() {
ForkJoinTask<?>[] oldA = array;
int size = oldA != null ? oldA.length << 1 : INITIAL_QUEUE_CAPACITY;
if (size > MAXIMUM_QUEUE_CAPACITY)
throw new RejectedExecutionException("Queue capacity exceeded");
int oldMask, t, b;
ForkJoinTask<?>[] a = array = new ForkJoinTask<?>[size];
if (oldA != null && (oldMask = oldA.length - 1) >= 0 &&
(t = top) - (b = base) > 0) {
int mask = size - 1;
do { // emulate poll from old array, push to new array
ForkJoinTask<?> x;
int oldj = ((b & oldMask) << ASHIFT) + ABASE;
int j = ((b & mask) << ASHIFT) + ABASE;
x = (ForkJoinTask<?>)U.getObjectVolatile(oldA, oldj);
if (x != null &&
U.compareAndSwapObject(oldA, oldj, x, null))
U.putObjectVolatile(a, j, x);
} while (++b != t);
}
return a;
}
@Override
void execute() {
EventExecutor executor = ctx.executor();
if (executor.inEventLoop()) {
callHandlerRemoved0(ctx);
} else {
try {
executor.execute(this);
} catch (RejectedExecutionException e) {
if (logger.isWarnEnabled()) {
logger.warn(
"Can't invoke handlerRemoved() as the EventExecutor {} rejected it," +
" removing handler {}.", executor, ctx.name(), e);
}
// remove0(...) was call before so just call AbstractChannelHandlerContext.setRemoved().
ctx.setRemoved();
}
}
}
@Override
public boolean offer(Runnable runnable) {
if (executor == null) {
throw new RejectedExecutionException("The task queue does not have executor!");
}
int currentPoolThreadSize = executor.getPoolSize();
// have free worker. put task into queue to let the worker deal with task.有自由工作者。将任务放入队列,让工人处理任务。
if (executor.getSubmittedTaskCount() < currentPoolThreadSize) {
return super.offer(runnable);
}
// return false to let executor create new worker.提交的任务数大于当前线程数,小于最大线程数,直接创建worker执行任务
if (currentPoolThreadSize < executor.getMaximumPoolSize()) {
return false;
}
// currentPoolThreadSize >= max 当前线程数大于最大线程数,放入队列
return super.offer(runnable);
}
@Override
public void subscribe(MultiSubscriber<? super Long> actual) {
IntervalRunnable runnable = new IntervalRunnable(actual);
actual.onSubscribe(runnable);
try {
if (initialDelay != null) {
executor.scheduleAtFixedRate(runnable, initialDelay.toMillis(), period.toMillis(),
TimeUnit.MILLISECONDS);
} else {
executor.scheduleAtFixedRate(runnable, 0, period.toMillis(),
TimeUnit.MILLISECONDS);
}
} catch (RejectedExecutionException ree) {
if (!runnable.cancelled.get()) {
actual.onFailure(new RejectedExecutionException(ree));
}
}
}
@Override
public void subscribe(CoreSubscriber<? super Long> actual) {
Worker w = timedScheduler.createWorker();
IntervalRunnable r = new IntervalRunnable(actual, w);
actual.onSubscribe(r);
try {
w.schedulePeriodically(r, initialDelay, period, unit);
}
catch (RejectedExecutionException ree) {
if (!r.cancelled) {
actual.onError(Operators.onRejectedExecution(ree, r, null, null,
actual.currentContext()));
}
}
}
/**
* Accept a new connection.
*/
private void handleAccept() {
final TNonblockingTransport client = doAccept();
if (client != null) {
// Pass this connection to a selector thread
final SelectorThread targetThread = threadChooser.nextThread();
if (args.acceptPolicy == Args.AcceptPolicy.FAST_ACCEPT || invoker == null) {
doAddAccept(targetThread, client);
} else {
// FAIR_ACCEPT
try {
invoker.submit(new Runnable() {
public void run() {
doAddAccept(targetThread, client);
}
});
} catch (RejectedExecutionException rx) {
LOGGER.warn("ExecutorService rejected accept registration!", rx);
// close immediately
client.close();
}
}
}
}
@Override
public ExceptionResponse getExceptionResponse(Exception exception) {
ExceptionResponse exceptionResponse = new ExceptionResponse();
if (exception instanceof GatewayException) {
GatewayException gatewayException = (GatewayException) exception;
exceptionResponse.setStatus(gatewayException.getStatus());
exceptionResponse.setContentType("text/plain");
exceptionResponse.setContent(gatewayException.getMessage());
} else if (exception instanceof ConnectException) {
exceptionResponse.setStatus(HttpResponseStatus.NOT_FOUND);
exceptionResponse.setContentType("text/plain");
exceptionResponse.setContent("connect server refused");
} else if (exception instanceof RejectedExecutionException) {
exceptionResponse.setStatus(HttpResponseStatus.TOO_MANY_REQUESTS);
exceptionResponse.setContentType("text/plain");
exceptionResponse.setContent("too many requests");
} else {
exceptionResponse.setStatus(HttpResponseStatus.INTERNAL_SERVER_ERROR);
exceptionResponse.setContentType("text/plain");
exceptionResponse.setContent(exception.getMessage());
}
return exceptionResponse;
}
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
LOGGER.warn("one task rejected, poolConfig={}, poolInfo={}", poolConfig, Utils.getPoolInfo(e));
if (!dumping) {
dumping = true;
dumpJVMInfo();
}
if (rejectedPolicy == REJECTED_POLICY_ABORT) {
throw new RejectedExecutionException("one task rejected, pool=" + poolConfig.getName());
} else if (rejectedPolicy == REJECTED_POLICY_CALLER_RUNS) {
if (!e.isShutdown()) {
r.run();
}
}
}
@Test
public void testRejectedFailure() throws Exception {
TestFuturePool<Void> pool = new TestFuturePool<Void>();
final AtomicBoolean result = new AtomicBoolean(false);
pool.executor.shutdown();
final CountDownLatch latch = new CountDownLatch(1);
Future<Void> future = pool.wrapper.apply(new Function0<Void>() {
public Void apply() {
result.set(true);
latch.countDown();
return null;
}
});
try {
Await.result(future);
fail("should have thrown");
} catch (RejectedExecutionException ex) {
}
assertFalse(result.get());
pool.wrapper.close();
latch.await();
assertTrue(result.get());
pool.shutdown();
}
@Test
public void testParallelLarger() {
MeanShift wine_serial = new MeanShift(wine,
new MeanShiftParameters().setVerbose(true)).fit();
System.out.println();
MeanShift wine_paral = null;
try {
wine_paral = new MeanShift(wine,
new MeanShiftParameters().setVerbose(true).setForceParallel(true)).fit();
} catch(OutOfMemoryError | RejectedExecutionException e) {
// don't propagate these...
return;
}
System.out.println();
assertTrue(Precision.equals(wine_serial.getBandwidth(), wine_paral.getBandwidth(), 1e-9));
assertTrue(wine_serial.silhouetteScore() == wine_paral.silhouetteScore());
assertTrue(VecUtils.equalsExactly(wine_serial.getLabels(), wine_paral.getLabels()));
}
@Override
public Future<?> submit(Runnable task) {
try {
if (this.taskDecorator == null && this.concurrentExecutor instanceof ExecutorService) {
return ((ExecutorService) this.concurrentExecutor).submit(task);
}
else {
FutureTask<Object> future = new FutureTask<>(task, null);
doExecute(this.concurrentExecutor, this.taskDecorator, future);
return future;
}
}
catch (RejectedExecutionException ex) {
throw new TaskRejectedException(
"Executor [" + this.concurrentExecutor + "] did not accept task: " + task, ex);
}
}
private Executor() {
this.executorService = getExecutorService();
this.eventBus =
new AsyncEventBus(
executorService,
(throwable, subscriberExceptionContext) -> {
if (!(throwable instanceof RejectedExecutionException)) {
log.catching(throwable);
}
});
Runtime.getRuntime()
.addShutdownHook(
new Thread(
() -> {
try {
shutdown(1);
} catch (Throwable t) {
// log.catching(t);
}
}));
}
@UiThread private void loadIcon(final @Nullable IconFilter filter, final IconConsumer consumer, final boolean need_badge) {
if (mCachedIcon == null) try {
new AsyncTask<Void, Void, Drawable>() {
@Override protected Drawable doInBackground(final Void... params) {
return need_badge ? loadIcon(context().getPackageManager()) : loadUnbadgedIconCompat(context().getPackageManager());
}
@Override protected void onPostExecute(final Drawable drawable) {
if (drawable == null) return; // Might be null if app is currently being removed.
final Drawable icon = (filter != null ? filter.process(drawable) : drawable);
mCachedIcon = icon;
consumer.accept(icon);
}
}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
} catch (final RejectedExecutionException e) {
Analytics.$().report(e); // For statistics purpose
} else consumer.accept(mCachedIcon);
}
/**
* Accept a new connection.
*/
private void handleAccept() {
final TNonblockingTransport client = doAccept();
if (client != null) {
// Pass this connection to a selector thread
final SelectorThread targetThread = threadChooser.nextThread();
if (args.acceptPolicy == Args.AcceptPolicy.FAST_ACCEPT || invoker == null) {
doAddAccept(targetThread, client);
} else {
// FAIR_ACCEPT
try {
invoker.submit(new Runnable() {
public void run() {
doAddAccept(targetThread, client);
}
});
} catch (RejectedExecutionException rx) {
LOGGER.warn("ExecutorService rejected accept registration!", rx);
// close immediately
client.close();
}
}
}
}
@Test
public void taskCapIsOnExecutorAndNotWorker() {
BoundedElasticScheduler
boundedElasticScheduler = afterTest.autoDispose(new BoundedElasticScheduler(1, 9, Thread::new, 10));
Worker worker1 = afterTest.autoDispose(boundedElasticScheduler.createWorker());
Worker worker2 = afterTest.autoDispose(boundedElasticScheduler.createWorker());
Worker worker3 = afterTest.autoDispose(boundedElasticScheduler.createWorker());
//schedule tasks for second and third workers as well as directly on scheduler to show worker1 is still impacted
worker2.schedule(() -> {}, 1000, TimeUnit.MILLISECONDS);
worker2.schedule(() -> {}, 1000, TimeUnit.MILLISECONDS);
worker2.schedulePeriodically(() -> {}, 1000, 100, TimeUnit.MILLISECONDS);
//enqueue tasks in second deferred worker
worker3.schedule(() -> {}, 1000, TimeUnit.MILLISECONDS);
worker3.schedule(() -> {}, 1000, TimeUnit.MILLISECONDS);
worker3.schedulePeriodically(() -> {}, 1000, 100, TimeUnit.MILLISECONDS);
//enqueue tasks on scheduler directly
boundedElasticScheduler.schedule(() -> {}, 1000, TimeUnit.MILLISECONDS);
boundedElasticScheduler.schedule(() -> {}, 1000, TimeUnit.MILLISECONDS);
boundedElasticScheduler.schedulePeriodically(() -> {}, 1000, 100, TimeUnit.MILLISECONDS);
//any attempt at scheduling more task should result in rejection
ScheduledThreadPoolExecutor threadPoolExecutor = (ScheduledThreadPoolExecutor) boundedElasticScheduler.boundedServices.busyQueue.peek().executor;
assertThat(threadPoolExecutor.getQueue().size()).as("queue full").isEqualTo(9);
assertThatExceptionOfType(RejectedExecutionException.class).as("worker1 immediate").isThrownBy(() -> worker1.schedule(() -> {}));
assertThatExceptionOfType(RejectedExecutionException.class).as("worker1 delayed").isThrownBy(() -> worker1.schedule(() -> {}, 100, TimeUnit.MILLISECONDS));
assertThatExceptionOfType(RejectedExecutionException.class).as("worker1 periodic").isThrownBy(() -> worker1.schedulePeriodically(() -> {}, 100, 100, TimeUnit.MILLISECONDS));
assertThatExceptionOfType(RejectedExecutionException.class).as("worker2 immediate").isThrownBy(() -> worker2.schedule(() -> {}));
assertThatExceptionOfType(RejectedExecutionException.class).as("worker2 delayed").isThrownBy(() -> worker2.schedule(() -> {}, 100, TimeUnit.MILLISECONDS));
assertThatExceptionOfType(RejectedExecutionException.class).as("worker2 periodic").isThrownBy(() -> worker2.schedulePeriodically(() -> {}, 100, 100, TimeUnit.MILLISECONDS));
assertThatExceptionOfType(RejectedExecutionException.class).as("scheduler immediate").isThrownBy(() -> boundedElasticScheduler.schedule(() -> {}));
assertThatExceptionOfType(RejectedExecutionException.class).as("scheduler delayed").isThrownBy(() -> boundedElasticScheduler.schedule(() -> {}, 100, TimeUnit.MILLISECONDS));
assertThatExceptionOfType(RejectedExecutionException.class).as("scheduler periodic").isThrownBy(() -> boundedElasticScheduler.schedulePeriodically(() -> {}, 100, 100, TimeUnit.MILLISECONDS));
}
@Override
public void execute(Runnable command) {
try {
super.execute(command);
} catch (RejectedExecutionException rx) {
if (super.getQueue() instanceof TaskQueue) {
TaskQueue queue = (TaskQueue)super.getQueue();
if (!queue.force(command)) {
throw new RejectedExecutionException(sm.getString("executorFactory.queue.full"));
}
}
}
}
/**
* {@inheritDoc}
*
* @see org.audit4j.core.schedule.TaskScheduler#scheduleWithFixedDelay(java.lang.Runnable, java.util.Date, long)
*
*/
@Override
public ScheduledFuture<?> scheduleWithFixedDelay(Runnable task, Date startTime, long delay) {
ScheduledExecutorService executor = getScheduledExecutor();
long initialDelay = startTime.getTime() - System.currentTimeMillis();
try {
return executor.scheduleWithFixedDelay(errorHandlingTask(task, true), initialDelay, delay,
TimeUnit.MILLISECONDS);
} catch (RejectedExecutionException ex) {
throw new TaskRejectedException("Executor [" + executor + "] did not accept task: " + task, ex);
}
}
@Override
public ScheduledFuture<?> schedule(final Runnable command, long delay, TimeUnit unit) {
if (shutdown) {
throw new RejectedExecutionException();
} else {
ScheduledFuture<?> scheduled = scheduler.schedule(worker, command, delay, unit);
if (shutdown && scheduled.cancel(false)) {
throw new RejectedExecutionException();
} else {
return scheduled;
}
}
}
@Override
public void execute(ThreadBoundEvent event) {
if (shuttingDown.get()) {
throw new RejectedExecutionException("The system is shutting down.");
}
if (event instanceof ThreadBoundRunnable) {
event = wrap((ThreadBoundRunnable<?>) event);
}
final RingBuffer<ThreadBoundEventWrapper> ringBuffer = this.disruptors.get(getBucket(event.getKey())).getRingBuffer();
// this method will wait when the buffer is overflowing ( using Lock.parkNanos(1) )
ringBuffer.publishEvent(translator, event);
}
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
if (executor.isShutdown()) {
throw new RejectedExecutionException("Threadpoolexecutor already shutdown");
} else {
try {
executor.getQueue().put(r);
} catch (InterruptedException e) {
throw new RejectedExecutionException(
"Thread was interrupted while waiting for space to be available in the threadpool", e);
}
}
}
@Test
public void timerDurationRejected() throws Exception {
Executor executor = from(new RejectAllScheduler());
expected.expect(ExecutionException.class);
expected.expectCause(instanceOf(RejectedExecutionException.class));
executor.timer(ofNanos(1)).toFuture().get();
}
@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);
}
}
@Override
public void processPacket(final Packet packet) {
try {
executor.execute(
new Runnable() {
@Override
public void run() {
handleInvitationRequest(new JID(packet.getFrom()));
}
});
} catch (RejectedExecutionException e) {
log.warn("Join Session request cannot be accepted (queue is full).", e);
}
}
@Override
public final void sendMessage(PcepMessage m) {
log.debug("Sending message to {}", channel.getRemoteAddress());
try {
channel.write(Collections.singletonList(m));
this.pktStats.addOutPacket();
} catch (RejectedExecutionException e) {
log.warn(e.getMessage());
if (!e.getMessage().contains(SHUTDOWN_MSG)) {
throw e;
}
}
}
void submit(Runnable runnable) {
try {
followersThreadPool.submit(runnable);
} catch (RejectedExecutionException err) {
LOGGER.log(Level.SEVERE, "rejected " + runnable, err);
}
}
@Override
public void handleException(Exception cce, EventLoop el)
{
teardown();
if (cce instanceof RejectedExecutionException && serverHelperExecutor.isTerminated()) {
logger.warn("Terminated Executor Exception for {}.", this, cce);
el.disconnect(this);
} else {
super.handleException(cce, el);
}
}