Java Code Examples for java.util.concurrent.RejectedExecutionException

The following are top voted examples for showing how to use java.util.concurrent.RejectedExecutionException. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: dhus-core   File: FairThreadPoolTaskExecutor.java   View source code 7 votes vote down vote up
@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);
   }
}
 
Example 2
Project: mango   File: NettyServerImpl.java   View source code 6 votes vote down vote up
/**处理客户端请求**/
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);
    }

}
 
Example 3
Project: GitHub   File: ConstrainedExecutorService.java   View source code 6 votes vote down vote up
/**
 * 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();
}
 
Example 4
Project: L2jBrasil   File: L2GamePacketHandler.java   View source code 6 votes vote down vote up
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());
		}
	}
}
 
Example 5
Project: monarch   File: InstantiatorRecoveryListener.java   View source code 6 votes vote down vote up
@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.
        }
      }
    }
  }
}
 
Example 6
Project: Espresso   File: AutoFocusManager.java   View source code 6 votes vote down vote up
@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);
		}
	}
}
 
Example 7
Project: monarch   File: DestroyRegionOperation.java   View source code 6 votes vote down vote up
/** 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
  }
}
 
Example 8
Project: JRediClients   File: RedissonExecutorService.java   View source code 6 votes vote down vote up
@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);
}
 
Example 9
Project: anyRTC-RTCP-Android   File: AutoFocusManager.java   View source code 6 votes vote down vote up
@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);
		}
	}
}
 
Example 10
Project: OpenJSharp   File: ForkJoinPool.java   View source code 6 votes vote down vote up
/**
 * 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;
}
 
Example 11
Project: monix-forkjoin   File: ForkJoinPool.java   View source code 6 votes vote down vote up
/**
 * 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;
}
 
Example 12
Project: monarch   File: ServerBlackList.java   View source code 6 votes vote down vote up
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.
    }

  }
}
 
Example 13
Project: boohee_v5.6   File: ExecutorScheduler.java   View source code 6 votes vote down vote up
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;
    }
}
 
Example 14
Project: apache-tomcat-7.0.73-with-comment   File: NioEndpoint.java   View source code 6 votes vote down vote up
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;
}
 
Example 15
Project: TPlayer   File: AutoFocusManager.java   View source code 6 votes vote down vote up
@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);
        }
    }
}
 
Example 16
Project: monarch   File: StatRecorderJUnitTest.java   View source code 6 votes vote down vote up
@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));
}
 
Example 17
Project: SmartButler   File: AutoFocusManager.java   View source code 6 votes vote down vote up
@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);
        }
    }
}
 
Example 18
Project: chromium-net-for-android   File: JavaUrlRequest.java   View source code 6 votes vote down vote up
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;
}
 
Example 19
Project: hadoop   File: NonAggregatingLogHandler.java   View source code 6 votes vote down vote up
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();
      }
    }
  }
}
 
Example 20
Project: lazycat   File: AprEndpoint.java   View source code 6 votes vote down vote up
/**
 * 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;
}
 
Example 21
Project: OSchina_resources_android   File: AutoFocusManager.java   View source code 6 votes vote down vote up
@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);
        }
    }
}
 
Example 22
Project: dhus-core   File: FairThreadPoolTaskExecutor.java   View source code 6 votes vote down vote up
@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);
   }
}
 
Example 23
Project: monarch   File: SerialGatewaySenderEventProcessor.java   View source code 6 votes vote down vote up
/**
 * 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;
    }
  }
}
 
Example 24
Project: lazycat   File: JIoEndpoint.java   View source code 6 votes vote down vote up
/**
 * 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;
}
 
Example 25
Project: monarch   File: GemFireCacheImpl.java   View source code 6 votes vote down vote up
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;
}
 
Example 26
Project: guava-mock   File: FuturesTest.java   View source code 6 votes vote down vote up
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);
  }
}
 
Example 27
Project: hekate   File: MessagingGateway.java   View source code 6 votes vote down vote up
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.
        }
    }
}
 
Example 28
Project: ditb   File: CompactSplitThread.java   View source code 6 votes vote down vote up
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);
  }
}
 
Example 29
Project: oscm   File: BasicBillingProxy.java   View source code 6 votes vote down vote up
<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;
}
 
Example 30
Project: androidscan   File: AutoFocusManager.java   View source code 5 votes vote down vote up
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);
        }
    }
}
 
Example 31
Project: L2jBrasil   File: L2GameClient.java   View source code 5 votes vote down vote up
@Override
protected void onDisconnection()
{
	// no long running tasks here, do it async
	try
	{
		ThreadPoolManager.getInstance().executeTask(new DisconnectTask());
	}
	catch (RejectedExecutionException e)
	{
		// server is closing
	}
}
 
Example 32
Project: L2jBrasil   File: ThreadPoolManager.java   View source code 5 votes vote down vote up
@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 */ }
}
 
Example 33
Project: easyhbase   File: MonitoredExecutorService.java   View source code 5 votes vote down vote up
@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;
    }
}
 
Example 34
Project: L2jBrasil   File: ThreadPoolManager.java   View source code 5 votes vote down vote up
@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 */ }
}
 
Example 35
Project: L2jBrasil   File: ThreadPoolManager.java   View source code 5 votes vote down vote up
@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 */ }
}
 
Example 36
Project: sponge   File: DefaultThreadPoolManager.java   View source code 5 votes vote down vote up
@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");
    }
}
 
Example 37
Project: incubator-netbeans   File: RequestProcessor.java   View source code 5 votes vote down vote up
/**
 * {@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;
}
 
Example 38
Project: incubator-netbeans   File: RequestProcessor.java   View source code 5 votes vote down vote up
/**
 * {@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;
}
 
Example 39
Project: lazycat   File: TaskQueue.java   View source code 5 votes vote down vote up
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
}
 
Example 40
Project: tvConnect_android   File: AutoFocusManager.java   View source code 5 votes vote down vote up
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);
    }
  }
}