@SuppressLint("NewApi") private synchronized void autoFocusAgainLater() { if (!stopped && outstandingTask == null) { AutoFocusTask newTask = new AutoFocusTask(); try { // Unnecessary, our app's min sdk is higher than 11. // if (Build.VERSION.SDK_INT >= 11) { // newTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); // } else { // // } newTask.execute(); outstandingTask = newTask; } catch (RejectedExecutionException ree) { Log.w(TAG, "Could not request auto focus", ree); } } }
/**处理客户端请求**/ private void processRpcRequest(final ChannelHandlerContext context, final DefaultRequest request) { final long processStartTime = System.currentTimeMillis(); try { this.pool.execute(new Runnable() { @Override public void run() { try { RpcContext.init(request); processRpcRequest(context, request, processStartTime); } finally { RpcContext.destroy(); } } }); } catch (RejectedExecutionException e) { DefaultResponse response = new DefaultResponse(); response.setRequestId(request.getRequestId()); response.setException(new RpcFrameworkException("process thread pool is full, reject")); response.setProcessTime(System.currentTimeMillis() - processStartTime); context.channel().write(response); } }
/** * Submit a task to be executed in the future. * @param runnable The task to be executed. */ @Override public void execute(Runnable runnable) { if (runnable == null) { throw new NullPointerException("runnable parameter is null"); } if (!mWorkQueue.offer(runnable)) { throw new RejectedExecutionException( mName + " queue is full, size=" + mWorkQueue.size()); } final int queueSize = mWorkQueue.size(); final int maxSize = mMaxQueueSize.get(); if ((queueSize > maxSize) && mMaxQueueSize.compareAndSet(maxSize, queueSize)) { FLog.v(TAG, "%s: max pending work in queue = %d", mName, queueSize); } // else, there was a race and another thread updated and logged the max queue size startWorkerIfNeeded(); }
public void execute(ReceivablePacket<L2GameClient> rp) { try { if (rp.getClient().getState() == GameClientState.IN_GAME) { ThreadPoolManager.getInstance().executePacket(rp); } else { ThreadPoolManager.getInstance().executeIOPacket(rp); } } catch (RejectedExecutionException e) { // if the server is shutdown we ignore if (!ThreadPoolManager.getInstance().isShutdown()) { _log.severe("Failed executing: "+rp.getClass().getSimpleName()+" for Client: "+rp.getClient().toString()); } } }
@Override public void endpointNowInUse(Endpoint endpoint) { int count = endpointCount.incrementAndGet(); final boolean isDebugEnabled = logger.isDebugEnabled(); if (isDebugEnabled) { logger.debug("InstantiatorRecoveryTask - EndpointNowInUse. Now have {} endpoints", count); } if (count == 1) { synchronized (recoveryScheduledLock) { if (!recoveryScheduled) { try { recoveryScheduled = true; background.execute(new RecoveryTask()); if (isDebugEnabled) { logger.debug("InstantiatorRecoveryTask - Scheduled Recovery Task"); } } catch (RejectedExecutionException e) { // ignore, the timer has been cancelled, which means we're shutting down. } } } } }
/** Return true if a reply should be sent */ @Override protected void basicProcess(final DistributionManager dm, final LocalRegion lclRgn) { Assert.assertTrue(this.serialNum != DistributionAdvisor.ILLEGAL_SERIAL); try { this.lockRoot = null; // may set lockRoot to the root region where destroyLock is acquired final boolean sendReply = true; // Part of fix for bug 34450 which was caused by a PR destroy region op // dead-locked with // a PR create region op. The create region op required an entry update // to release a // DLock needed by the PR destroy.. by moving the destroy to the waiting // pool, the entry // update is allowed to complete. dm.getWaitingThreadPool().execute(destroyOp(dm, lclRgn, sendReply)); } catch (RejectedExecutionException e) { // rejected while trying to execute destroy thread // must be shutting down, just quit } }
@Override public RExecutorBatchFuture submit(Callable<?> ...tasks) { if (tasks.length == 0) { throw new NullPointerException("Tasks are not defined"); } List<RExecutorFuture<?>> result = new ArrayList<RExecutorFuture<?>>(); TasksBatchService executorRemoteService = createBatchService(); RemoteExecutorServiceAsync asyncService = executorRemoteService.get(RemoteExecutorServiceAsync.class, RemoteInvocationOptions.defaults().noAck().expectResultWithin(1, TimeUnit.DAYS)); for (Callable<?> task : tasks) { check(task); byte[] classBody = getClassBody(task); byte[] state = encode(task); RemotePromise<?> promise = (RemotePromise<?>)asyncService.executeCallable(task.getClass().getName(), classBody, state); RedissonExecutorFuture<?> executorFuture = new RedissonExecutorFuture(promise, promise.getRequestId()); result.add(executorFuture); } List<Boolean> addResult = (List<Boolean>) executorRemoteService.executeAdd(); if (!addResult.get(0)) { throw new RejectedExecutionException("Tasks have been rejected. ExecutorService is in shutdown state"); } return new RedissonExecutorBatchFuture(result); }
@SuppressLint("NewApi") synchronized void autoFocusAgainLater() { if (!stopped && outstandingTask == null) { AutoFocusTask newTask = new AutoFocusTask(); try { if (Build.VERSION.SDK_INT >= 11) { newTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } else { newTask.execute(); } outstandingTask = newTask; } catch (RejectedExecutionException ree) { Log.w(TAG, "Could not request auto focus", ree); } } }
/** * 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; }
/** * 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 { 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; }
public void addFailure() { if (blacklist.contains(location)) { // A second failure must have happened before we added // this server to the blacklist. Don't count that failure. return; } long failures = consecutiveFailures.incrementAndGet(); if (failures >= THRESHOLD) { if (logger.isDebugEnabled()) { logger.debug("Blacklisting server {} for {}ms because it had {} consecutive failures", location, pingInterval, failures); } blacklist.add(location); broadcaster.serverAdded(location); try { background.schedule(new ExpireBlackListTask(location), pingInterval, TimeUnit.MILLISECONDS); } catch (RejectedExecutionException e) { // ignore, the timer has been cancelled, which means we're shutting down. } } }
public Subscription schedule(Action0 action) { if (isUnsubscribed()) { return Subscriptions.unsubscribed(); } Subscription ea = new ScheduledAction(action, this.tasks); this.tasks.add(ea); this.queue.offer(ea); if (this.wip.getAndIncrement() != 0) { return ea; } try { this.executor.execute(this); return ea; } catch (RejectedExecutionException t) { this.tasks.remove(ea); this.wip.decrementAndGet(); RxJavaPlugins.getInstance().getErrorHandler().handleError(t); throw t; } }
public boolean processSocket(NioChannel socket, SocketStatus status, boolean dispatch) { try { KeyAttachment attachment = (KeyAttachment)socket.getAttachment(); if (attachment == null) { return false; } attachment.setCometNotify(false); //will get reset upon next reg SocketProcessor sc = processorCache.poll(); if ( sc == null ) sc = new SocketProcessor(socket,status); else sc.reset(socket,status); if ( dispatch && getExecutor()!=null ) getExecutor().execute(sc); else sc.run(); } catch (RejectedExecutionException rx) { log.warn("Socket processing request was rejected for:"+socket,rx); return false; } catch (Throwable t) { ExceptionUtils.handleThrowable(t); // This means we got an OOM or similar creating a thread, or that // the pool and its queue are full log.error(sm.getString("endpoint.process.fail"), t); return false; } return true; }
@SuppressLint("NewApi") private synchronized void autoFocusAgainLater() { if (!stopped && outstandingTask == null) { AutoFocusTask newTask = new AutoFocusTask(); try { if (Build.VERSION.SDK_INT >= 11) { newTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } else { newTask.execute(); } outstandingTask = newTask; } catch (RejectedExecutionException ree) { Log.w(TAG, "Could not request auto focus", ree); } } }
@Test public void recorderHandlesRejectedExecution() throws Exception { Message msg = mock(Message.class); when(msg.getHeader(any(Short.class))).thenReturn(Header.createDataHeader(1L, (short) 1, true)); when(msg.size()).thenReturn(150L); // GEODE-1178, the TP protocol may throw a RejectedExecutionException & StatRecorder should // retry when(mockDownProtocol.down(any(Event.class))).thenThrow(new RejectedExecutionException()); // after the first down() throws an exception we want StatRecorder to retry, so // we set the Manager to say no shutdown is in progress the first time and then say // one IS in progress so we can break out of the StatRecorder exception handling loop when(services.getCancelCriterion()).thenReturn(new Services().getCancelCriterion()); Manager manager = mock(Manager.class); when(services.getManager()).thenReturn(manager); when(manager.shutdownInProgress()).thenReturn(Boolean.FALSE, Boolean.TRUE); verify(mockDownProtocol, never()).down(isA(Event.class)); Event evt = new Event(Event.MSG, msg); recorder.down(evt); verify(mockDownProtocol, times(2)).down(isA(Event.class)); }
OutputStreamDataSink(final Executor userExecutor, Executor executor, HttpURLConnection urlConnection, UploadDataProvider provider) { this.mUserExecutor = new Executor() { @Override public void execute(Runnable runnable) { try { userExecutor.execute(runnable); } catch (RejectedExecutionException e) { enterUploadErrorState(e); } } }; this.mExecutor = executor; this.mUrlConnection = urlConnection; this.mUploadProvider = provider; }
private void recover() throws IOException { if (stateStore.canRecover()) { RecoveredLogDeleterState state = stateStore.loadLogDeleterState(); long now = System.currentTimeMillis(); for (Map.Entry<ApplicationId, LogDeleterProto> entry : state.getLogDeleterMap().entrySet()) { ApplicationId appId = entry.getKey(); LogDeleterProto proto = entry.getValue(); long deleteDelayMsec = proto.getDeletionTime() - now; if (LOG.isDebugEnabled()) { LOG.debug("Scheduling deletion of " + appId + " logs in " + deleteDelayMsec + " msec"); } LogDeleterRunnable logDeleter = new LogDeleterRunnable(proto.getUser(), appId); try { sched.schedule(logDeleter, deleteDelayMsec, TimeUnit.MILLISECONDS); } catch (RejectedExecutionException e) { // Handling this event in local thread before starting threads // or after calling sched.shutdownNow(). logDeleter.run(); } } } }
/** * Process given socket. Called in non-comet mode, typically keep alive or * upgraded protocol. */ public boolean processSocket(long socket, SocketStatus status) { try { Executor executor = getExecutor(); if (executor == null) { log.warn(sm.getString("endpoint.warn.noExector", Long.valueOf(socket), null)); } else { SocketWrapper<Long> wrapper = connections.get(Long.valueOf(socket)); // Make sure connection hasn't been closed if (wrapper != null) { executor.execute(new SocketProcessor(wrapper, status)); } } } catch (RejectedExecutionException x) { log.warn("Socket processing request was rejected for:" + socket, x); return false; } catch (Throwable t) { ExceptionUtils.handleThrowable(t); // This means we got an OOM or similar creating a thread, or that // the pool and its queue are full log.error(sm.getString("endpoint.process.fail"), t); return false; } return true; }
@Override public ListenableFuture<?> submitListenable (Runnable task) { ExecutorService executor = getThreadPoolExecutor (); try { ListenableFutureTask<Object> future = new ListenableFutureTask<Object> (task, null); executor.execute (future); return future; } catch (RejectedExecutionException ex) { throw new TaskRejectedException ("Executor [" + executor + "] did not accept task: " + task, ex); } }
@Override public <T> ListenableFuture<T> submitListenable (Callable<T> task) { ExecutorService executor = getThreadPoolExecutor (); try { ListenableFutureTask<T> future = new ListenableFutureTask<T> (task); executor.execute (future); return future; } catch (RejectedExecutionException ex) { throw new TaskRejectedException ("Executor [" + executor + "] did not accept task: " + task, ex); } }
/** * Update an unprocessed event in the unprocessed events map. This method is called by a primary * <code>Gateway</code> (through * {@link org.apache.geode.internal.cache.wan.serial.SerialSecondaryGatewayListener#afterCreate} ) * to notify the secondary <code>Gateway</code> that an event has been added to the queue. Once an * event has been added to the queue, the secondary no longer needs to keep track of it in the * unprocessed events map. The complexity of this method is the fact that the event could be * processed first by either the primary or secondary <code>Gateway</code>. * * If the primary processes the event first, the map will not contain an entry for the event. It * will be added to the map in this case so that when the secondary processes it, it will know * that the primary has already processed it, and it can be safely removed. * * If the secondary processes the event first, the map will already contain an entry for the * event. In this case, the event can be removed from the map. * * @param gatewayEvent The event being processed */ protected void handlePrimaryEvent(final GatewaySenderEventImpl gatewayEvent) { Executor my_executor = this.executor; synchronized (listenerObjectLock) { if (my_executor == null) { // should mean we are now primary return; } try { my_executor.execute(new Runnable() { public void run() { basicHandlePrimaryEvent(gatewayEvent); } }); } catch (RejectedExecutionException ex) { throw ex; } } }
/** * Process a new connection from a new client. Wraps the socket so * keep-alive and other attributes can be tracked and then passes the socket * to the executor for processing. * * @param socket * The socket associated with the client. * * @return <code>true</code> if the socket is passed to the executor, * <code>false</code> if something went wrong or if the endpoint is * shutting down. Returning <code>false</code> is an indication to * close the socket immediately. */ protected boolean processSocket(Socket socket) { // Process the request from this socket try { SocketWrapper<Socket> wrapper = new SocketWrapper<Socket>(socket); wrapper.setKeepAliveLeft(getMaxKeepAliveRequests()); wrapper.setSecure(isSSLEnabled()); // During shutdown, executor may be null - avoid NPE if (!running) { return false; } getExecutor().execute(new SocketProcessor(wrapper)); } catch (RejectedExecutionException x) { log.warn("Socket processing request was rejected for:" + socket, x); return false; } catch (Throwable t) { ExceptionUtils.handleThrowable(t); // This means we got an OOM or similar creating a thread, or that // the pool and its queue are full log.error(sm.getString("endpoint.process.fail"), t); return false; } return true; }
public boolean executeDiskStoreTask(DiskStoreTask r) { synchronized (this.diskStoreTaskSync) { if (!this.diskStoreTaskSync.get()) { if (this.diskStoreTaskPool == null) { createDiskStoreTaskPool(); } try { this.diskStoreTaskPool.execute(r); return true; } catch (RejectedExecutionException ex) { if (logger.isDebugEnabled()) { logger.debug("Ignored compact schedule during shutdown", ex); } } } } return false; }
public void testCatchingAsync_rejectionPropagatesToOutput() throws Exception { SettableFuture<String> input = SettableFuture.create(); ListenableFuture<String> transformed = catchingAsync( input, Throwable.class, constantAsyncFunction(immediateFuture("foo")), REJECTING_EXECUTOR); input.setException(new Exception()); try { getDone(transformed); fail(); } catch (ExecutionException expected) { assertThat(expected.getCause()).isInstanceOf(RejectedExecutionException.class); } }
private void doScheduleTimeout(long timeout, MessageContext<T> ctx, Object callback) { if (!ctx.isCompleted()) { try { Future<?> future = ctx.worker().executeDeferred(timeout, () -> { if (ctx.completeOnTimeout()) { T msg = ctx.originalMessage(); doNotifyOnError(callback, new MessageTimeoutException("Messaging operation timed out [message=" + msg + ']')); } }); ctx.setTimeoutFuture(future); } catch (RejectedExecutionException e) { // Ignore since this error means that channel is closed. // In such case we can ignore timeout notification because messaging context will be notified by another error. } } }
public synchronized void requestSplit(final Region r, byte[] midKey, User user) { if (midKey == null) { LOG.debug("Region " + r.getRegionInfo().getRegionNameAsString() + " not splittable because midkey=null"); if (((HRegion)r).shouldForceSplit()) { ((HRegion)r).clearSplit(); } return; } try { this.splits.execute(new SplitRequest(r, midKey, this.server, user)); if (LOG.isDebugEnabled()) { LOG.debug("Split requested for " + r + ". " + this); } } catch (RejectedExecutionException ree) { LOG.info("Could not execute split for " + r, ree); } }
<T> Future<T> submitAdapterCall(Callable<T> callable) throws BillingApplicationException { ExecutorService executor = getSingleThreadExecutor(); Future<T> future = null; try { future = executor.submit(callable); } catch (RejectedExecutionException e) { logger.logError(Log4jLogger.SYSTEM_LOG, e, LogMessageIdentifier.ERROR_EXECUTION_OF_BILLING_APPLICATION_TASK_REJECTED); throw new BillingApplicationException( "Call to Billing Adapter failed", new BillingAdapterConnectionException( "The execution of the billing application task was rejected")); } return future; }
private synchronized void autoFocusAgainLater() { if (!stopped && outstandingTask == null) { AutoFocusTask newTask = new AutoFocusTask(); try { if (Build.VERSION.SDK_INT >= 11) { newTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } else { newTask.execute(); } outstandingTask = newTask; } catch (RejectedExecutionException ree) { Log.w(TAG, "Could not request auto focus", ree); } } }
@Override protected void onDisconnection() { // no long running tasks here, do it async try { ThreadPoolManager.getInstance().executeTask(new DisconnectTask()); } catch (RejectedExecutionException e) { // server is closing } }
@SuppressWarnings("rawtypes") public ScheduledFuture scheduleEffect(Runnable r, long delay) { try { if (delay < 0) delay = 0; return _effectsScheduledThreadPool.schedule(r, delay, TimeUnit.MILLISECONDS); } catch (RejectedExecutionException e) { return null; /* shutdown, ignore */ } }
@Override public <T> T invokeAny(Collection<? extends Callable<T>> callables) throws ExecutionException, InterruptedException { submitted.mark(callables.size()); Collection<? extends Callable<T>> instrumented = instrument(callables); try { return delegate.invokeAny(instrumented); } catch (RejectedExecutionException ree) { rejected.mark(callables.size()); throw ree; } }
@SuppressWarnings("rawtypes") public ScheduledFuture scheduleGeneral(Runnable r, long delay) { try { if (delay < 0) delay = 0; return _generalScheduledThreadPool.schedule(r, delay, TimeUnit.MILLISECONDS); } catch (RejectedExecutionException e) { return null; /* shutdown, ignore */ } }
@SuppressWarnings("rawtypes") public ScheduledFuture scheduleGeneralAtFixedRate(Runnable r, long initial, long delay) { try { if (delay < 0) delay = 0; if (initial < 0) initial = 0; return _generalScheduledThreadPool.scheduleAtFixedRate(r, initial, delay, TimeUnit.MILLISECONDS); } catch (RejectedExecutionException e) { return null; /* shutdown, ignore */ } }
@Override public void rejectedExecution(Runnable runnable, ThreadPoolExecutor executor) { if (!executor.isShutdown()) { try { executor.getQueue().put(runnable); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RejectedExecutionException("Interrupted", e); } } else { throw new RejectedExecutionException("Executor has been shut down"); } }
/** * {@inheritDoc} * <p/> * <b>Note:</b> If the passed {@link java.util.concurrent.Callable} implements * {@link org.openide.util.Cancellable}, then that object's {@link org.openide.util.Cancellable#cancel()} * method will be called if {@link java.util.concurrent.Future#cancel(boolean)} is invoked. * If <code>Cancellable.cancel()</code> returns false, then <i>the job will <u>not</u> be * cancelled</i>. * @since org.openide.util 8.2 */ @Override public <T> Future<T> submit(Callable<T> task) { Parameters.notNull("task", task); //NOI18N if (stopped) { throw new RejectedExecutionException("Request Processor already " + //NOI18N "stopped"); //NOI18N } RPFutureTask<T> result = new RPFutureTask<T>(task); Task t = create(result); result.setTask(t); t.schedule(0); return result; }
/** * {@inheritDoc} * <b>Note:</b> If the passed {@link java.lang.Runnable} implements * {@link org.openide.util.Cancellable}, then that object's {@link org.openide.util.Cancellable#cancel()} * method will be called if {@link java.util.concurrent.Future#cancel(boolean)} is invoked. * If <code>Cancellable.cancel()</code> returns false, then <i>the job will <u>not</u> be * cancelled</i>. * @since org.openide.util 8.2 */ @Override public <T> Future<T> submit(Runnable task, T predefinedResult) { Parameters.notNull("task", task); //NOI18N if (stopped) { throw new RejectedExecutionException("Request Processor already " + //NOI18N "stopped"); //NOI18N } RPFutureTask<T> result = new RPFutureTask<T>(task, predefinedResult); Task t = create(result); result.setTask(t); t.schedule(0); return result; }
public boolean force(Runnable o, long timeout, TimeUnit unit) throws InterruptedException { if (parent.isShutdown()) throw new RejectedExecutionException("Executor not running, can't force a command into the queue"); return super.offer(o, timeout, unit); // forces the item onto the queue, // to be used if the task is // rejected }
private synchronized void autoFocusAgainLater() { if (!stopped && outstandingTask == null) { AutoFocusTask newTask = new AutoFocusTask(); try { newTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); outstandingTask = newTask; } catch (RejectedExecutionException ree) { Log.w(TAG, "Could not request auto focus", ree); } } }