java.util.concurrent.Executor Java Examples

The following examples show how to use java.util.concurrent.Executor. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File:    From crate with Apache License 2.0 6 votes vote down vote up
void loopRead(Executor executor) {
    executor.execute(new AbstractRunnable() {
        public void onFailure(Exception e) {
            if (isOpen.get()) {
                try {
                    onException(MockChannel.this, e);
                } catch (Exception ex) {
                    logger.warn("failed on handling exception", ex);
                    IOUtils.closeWhileHandlingException(MockChannel.this); // pure paranoia

        protected void doRun() throws Exception {
            StreamInput input = new InputStreamStreamInput(new BufferedInputStream(activeChannel.getInputStream()));
            // There is a (slim) chance that we get interrupted right after a loop iteration, so check explicitly
            while (isOpen.get() && !Thread.currentThread().isInterrupted()) {
                cancellableThreads.executeIO(() -> readMessage(MockChannel.this, input));
Example #2
Source File:    From ignite with Apache License 2.0 6 votes vote down vote up
/** {@inheritDoc} */
@Override public void setNetworkTimeout(Executor executor, int ms) throws SQLException {

    if (ms < 0)
        throw new SQLException("Network timeout cannot be negative.");

    SecurityManager secMgr = System.getSecurityManager();

    if (secMgr != null)
        secMgr.checkPermission(new SQLPermission(SET_NETWORK_TIMEOUT_PERM));

    netTimeout = ms;

    if (partitionAwareness) {
        for (JdbcThinTcpIo clioIo : ios.values())
Example #3
Source File:    From hottub with GNU General Public License v2.0 6 votes vote down vote up
 * Factory method. Construct concrete handler in depends from {@code path}.
 * @param path     the path to process
 * @param executor executor used for compile task invocation
 * @throws NullPointerException if {@code path} or {@code executor} is
 *                              {@code null}
public static PathHandler create(String path, Executor executor) {
    Matcher matcher = JAR_IN_DIR_PATTERN.matcher(path);
    if (matcher.matches()) {
        path =;
        path = path.isEmpty() ? "." : path;
        return new ClassPathJarInDirEntry(Paths.get(path), executor);
    } else {
        path = path.isEmpty() ? "." : path;
        Path p = Paths.get(path);
        if (isJarFile(p)) {
            return new ClassPathJarEntry(p, executor);
        } else if (isListFile(p)) {
            return new ClassesListInFile(p, executor);
        } else {
            return new ClassPathDirEntry(p, executor);
Example #4
Source File:    From armeria with Apache License 2.0 6 votes vote down vote up
private HttpResponse read(Executor fileReadExecutor, ByteBufAllocator alloc,
                          @Nullable HttpFileAttributes attrs) {
    final ResponseHeaders headers = readHeaders(attrs);
    if (headers == null) {
        return null;

    final long length = attrs.length();
    if (length == 0) {
        // No need to stream an empty file.
        return HttpResponse.of(headers);

    try {
        return doRead(headers, length, fileReadExecutor, alloc);
    } catch (IOException e) {
        return Exceptions.throwUnsafely(e);
Example #5
Source File:    From apollo-android with MIT License 6 votes vote down vote up
public void interceptAsync(@NotNull final InterceptorRequest request, @NotNull final ApolloInterceptorChain chain,
    @NotNull final Executor dispatcher, @NotNull final CallBack callBack) {
  InterceptorRequest cacheRequest = request.toBuilder().fetchFromCache(true).build();
  chain.proceedAsync(cacheRequest, dispatcher, new CallBack() {
    @Override public void onResponse(@NotNull InterceptorResponse response) {

    @Override public void onFailure(@NotNull ApolloException e) {
      if (!disposed) {
        InterceptorRequest networkRequest = request.toBuilder().fetchFromCache(false).build();
        chain.proceedAsync(networkRequest, dispatcher, callBack);

    @Override public void onCompleted() {

    @Override public void onFetch(FetchSourceType sourceType) {
Example #6
Source File:    From incubator-retired-wave with Apache License 2.0 6 votes vote down vote up
public LucenePerUserWaveViewHandlerImpl(IndexDirectory directory,
                                        ReadableWaveletDataProvider waveletProvider,
                                        @Named(CoreSettingsNames.WAVE_SERVER_DOMAIN) String domain,
                                        @IndexExecutor Executor executor) {
  this.waveletProvider = waveletProvider;
  this.executor = executor;
  analyzer = new StandardAnalyzer(LUCENE_VERSION);
  try {
    IndexWriterConfig indexConfig = new IndexWriterConfig(LUCENE_VERSION, analyzer);
    indexWriter = new IndexWriter(directory.getDirectory(), indexConfig);
    nrtManager = new NRTManager(indexWriter, new WaveSearchWarmer(domain));
  } catch (IOException ex) {
    throw new IndexException(ex);

  nrtManagerReopenThread = new NRTManagerReopenThread(nrtManager, MAX_STALE_SEC, MIN_STALE_SEC);
Example #7
Source File:    From threadly with Mozilla Public License 2.0 5 votes vote down vote up
public ListenableFuture<T> resultCallback(Consumer<? super T> callback, Executor executor, 
                                          ListenerOptimizationStrategy optimize) {
  if (invokeCompletedDirectly(executor, optimize)) {
  } else {
    executor.execute(() -> callback.accept(result));
  return this;
Example #8
Source File:    From dubbo-2.6.5 with Apache License 2.0 5 votes vote down vote up
static void mutliThreadTest(int tc, final int port) throws Exception {
    Executor exec = Executors.newFixedThreadPool(tc);
    for (int i = 0; i < tc; i++)
        exec.execute(new Runnable() {
            public void run() {
                try {
                } catch (Exception e) {
Example #9
Source File:    From flink with Apache License 2.0 5 votes vote down vote up
public CompletableFuture<T> triggerCheckpoint(long checkpointId, long timestamp, final Executor executor) throws Exception {
	final Executor wrappedExecutor = command -> executor.execute(new WrappedCommand(userClassLoader, command));

	return LambdaUtil.withContextClassLoader(
			() -> hook.triggerCheckpoint(checkpointId, timestamp, wrappedExecutor));
Example #10
Source File:    From couchbase-lite-java with Apache License 2.0 5 votes vote down vote up
 * Adds a listener for receiving the replication status of the specified document with an executor on which
 * the status will be posted to the listener. If the executor is not specified, the status will be delivered
 * on the UI thread for the Android platform and on an arbitrary thread for the Java platform.
 * @param executor executor on which events will be delivered
 * @param listener callback
public ListenerToken addDocumentReplicationListener(
    @Nullable Executor executor,
    @NonNull DocumentReplicationListener listener) {
    Preconditions.assertNotNull(listener, "listener");
    synchronized (lock) {
        final DocumentReplicationListenerToken token = new DocumentReplicationListenerToken(executor, listener);
        return token;
Example #11
Source File:    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
 * Adds a listener for state change event.
 * <p>The {@code executor} must be one that can run RPC call listeners.
void notifyWhenStateChanged(Runnable callback, Executor executor, ConnectivityState source) {
  checkNotNull(callback, "callback");
  checkNotNull(executor, "executor");
  checkNotNull(source, "source");

  Listener stateChangeListener = new Listener(callback, executor);
  if (state != source) {
  } else {
Example #12
Source File:    From caffeine with Apache License 2.0 5 votes vote down vote up
public Future<?> schedule(Executor executor, Runnable command, long delay, TimeUnit unit) {

  try {
    Executor scheduler = (Executor) delayedExecutor.invoke(
        CompletableFuture.class, delay, unit, executor);
    return CompletableFuture.runAsync(command, scheduler);
  } catch (IllegalAccessException | InvocationTargetException e) {
    throw new RuntimeException(e);
Example #13
Source File:    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
 * Adds a listener that is called periodically while the ControllableTask executes.
 * @param executor the executor to use to call the listener
 * @return this Task
public StorageTask<ResultT> addOnProgressListener(
    @NonNull Executor executor, @NonNull OnProgressListener<? super ResultT> listener) {
  progressManager.addListener(null, executor, listener);
  return this;
Example #14
Source File:    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
AcceptEither(CompletableFuture<? extends T> src,
             CompletableFuture<? extends T> snd,
             Consumer<? super T> fn,
             CompletableFuture<Void> dst,
             Executor executor) {
    this.src = src; this.snd = snd;
    this.fn = fn; this.dst = dst;
    this.executor = executor;
Example #15
Source File:    From FacebookImageShareIntent with MIT License 5 votes vote down vote up
@SmallTest @MediumTest @LargeTest
public void testSetExecutor() {
    final ConditionVariable condition = new ConditionVariable();

    final Runnable runnable = new Runnable() {
        public void run() { }

    final Executor executor = new Executor() {
        public void execute(Runnable command) {
            assertEquals(runnable, command);


    Executor original = Settings.getExecutor();
    try {

        boolean success = condition.block(5000);
    } finally {
Example #16
Source File:    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
 * @param root     root path to process
 * @param executor executor used for process task invocation
 * @throws NullPointerException if {@code root} or {@code executor} is
 *                              {@code null}
protected PathHandler(Path root, Executor executor) {
    this.root = root.normalize();
    this.executor = executor;
    this.loader = ClassLoader.getSystemClassLoader();
Example #17
Source File:    From grpc-java with Apache License 2.0 5 votes vote down vote up
public void testExecutor_custom() throws Exception {
  final List<InetAddress> answer = createAddressList(2);
  final AtomicInteger executions = new AtomicInteger();

  NameResolver.Args args =
              new Executor() {
                public void execute(Runnable command) {

  DnsNameResolver resolver =
      newResolver("", Stopwatch.createUnstarted(), false, args);
  AddressResolver mockResolver = mock(AddressResolver.class);

  assertEquals(0, fakeExecutor.runDueTasks());
  assertAnswerMatches(answer, 81, resultCaptor.getValue());
  assertEquals(0, fakeClock.numPendingTasks());


Example #18
Source File:    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
private Executor getSerialExecutor(InternalDistributedMember sender) {
     return this.serialQueuedExecutorPool.getThrottledSerialExecutor(sender);
   } else {
     return this.serialThread;
Example #19
Source File:    From postgres-async-driver with Apache License 2.0 5 votes vote down vote up
private ProtocolStream newProtocolStream(Executor futuresExecutor) {
    return new NettyProtocolStream(
            new InetSocketAddress(properties.getHostname(), properties.getPort()),
Example #20
Source File:    From jenetics with Apache License 2.0 5 votes vote down vote up
	final Function<? super Genotype<G>, ? extends C> function,
	final Executor executor
) {
	_function = requireNonNull(function);
	_executor = requireNonNull(executor);
Example #21
Source File:    From difido-reports with Apache License 2.0 5 votes vote down vote up
 * Configuration of the async executor. This is used for writing to the file
 * system and it is very important that there will be no more then one
 * thread in the pool.
public Executor getAsyncExecutor() {
	executor = new ThreadPoolTaskExecutor();
	// Do not change the number of threads here
	// Do not change the number of threads here
	return executor;
Example #22
Source File:    From crate with Apache License 2.0 5 votes vote down vote up
 * Execute the given runnable using the executor.
 * If the executor throws a RejectedExecutionException the runnable is invoked directly in the calling thread
public static void forceExecute(Executor executor, Runnable runnable) {
    try {
    } catch (RejectedExecutionException e) {;
Example #23
Source File:    From busybee with Apache License 2.0 5 votes vote down vote up
public Executor build() {
    if (wrappedExecutor == null) {
        throw new NullPointerException("BusyBeeExecutorWrapper must has an underlying executor to wrap, can't be null.");
    if (busyBee instanceof NoOpBusyBee) {
        return wrappedExecutor;
    } else {
        return new BusyBeeExecutorWrapper(busyBee, category, wrappedExecutor);
Example #24
Source File:    From Flink-CEPplus with Apache License 2.0 5 votes vote down vote up
public void testComposeAsyncIfNotDone() {
	testFutureContinuation((CompletableFuture<?> future, Executor executor) ->
			o -> null));
Example #25
Source File:    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
public CompletableFuture<Void> acceptEitherAsync
    (CompletionStage<? extends T> other,
     Consumer<? super T> action,
     Executor executor) {
    if (executor == null) throw new NullPointerException();
    return doAcceptEither(other.toCompletableFuture(), action, executor);
Example #26
Source File:    From Flink-CEPplus with Apache License 2.0 5 votes vote down vote up
 * Builds the ExecutionGraph from the JobGraph.
 * If a prior execution graph exists, the JobGraph will be attached. If no prior execution
 * graph exists, then the JobGraph will become attach to a new empty execution graph.
public static ExecutionGraph buildGraph(
		@Nullable ExecutionGraph prior,
		JobGraph jobGraph,
		Configuration jobManagerConfig,
		ScheduledExecutorService futureExecutor,
		Executor ioExecutor,
		SlotProvider slotProvider,
		ClassLoader classLoader,
		CheckpointRecoveryFactory recoveryFactory,
		Time rpcTimeout,
		RestartStrategy restartStrategy,
		MetricGroup metrics,
		BlobWriter blobWriter,
		Time allocationTimeout,
		Logger log)
	throws JobExecutionException, JobException {

	return buildGraph(
Example #27
Source File:    From netbeans with Apache License 2.0 5 votes vote down vote up
TaskModel(Executor eventExecutor) {
    selectionModel = new DefaultListSelectionModel();
    model = new DefaultListModel<>();
    dataListeners = new LinkedHashSet<ListDataListener>();
    selectionListeners = new LinkedHashSet<ListSelectionListener>();
    TaskListener list = new TaskListener();
    this.eventExecutor = eventExecutor;
Example #28
Source File:    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
Executor executor() {
  if (LOADING_MODE_BLOCKING.equals(loadingMode())) {
    return Runnable::run;

  return Executors.newSingleThreadExecutor();
Example #29
Source File:    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
    TokenChangeListener listener,
    Executor executor,
    Map<String, Object> authVariable) {
  this.listener = checkNotNull(listener, "Listener must not be null");
  this.executor = checkNotNull(executor, "Executor must not be null");
  this.authVariable = authVariable;
Example #30
Source File:    From jdk8u-dev-jdk with GNU General Public License v2.0 4 votes vote down vote up
UniCompose(Executor executor, CompletableFuture<V> dep,
           CompletableFuture<T> src,
           Function<? super T, ? extends CompletionStage<V>> fn) {
    super(executor, dep, src); this.fn = fn;