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: MockTcpTransport.java    From crate with Apache License 2.0 6 votes vote down vote up
void loopRead(Executor executor) {
    executor.execute(new AbstractRunnable() {
        @Override
        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
                }
            }
        }

        @Override
        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: JdbcThinConnection.java    From ignite with Apache License 2.0 6 votes vote down vote up
/** {@inheritDoc} */
@Override public void setNetworkTimeout(Executor executor, int ms) throws SQLException {
    ensureNotClosed();

    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())
            clioIo.timeout(ms);
    }
    else
        singleIo.timeout(ms);
}
 
Example #3
Source File: PathHandler.java    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) {
    Objects.requireNonNull(path);
    Objects.requireNonNull(executor);
    Matcher matcher = JAR_IN_DIR_PATTERN.matcher(path);
    if (matcher.matches()) {
        path = matcher.group(1);
        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: AbstractHttpFile.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Nullable
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: CacheFirstFetcher.java    From apollo-android with MIT License 6 votes vote down vote up
@Override
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) {
      callBack.onResponse(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() {
      callBack.onCompleted();
    }

    @Override public void onFetch(FetchSourceType sourceType) {
      callBack.onFetch(sourceType);
    }
  });
}
 
Example #6
Source File: LucenePerUserWaveViewHandlerImpl.java    From incubator-retired-wave with Apache License 2.0 6 votes vote down vote up
@Inject
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);
    indexConfig.setOpenMode(OpenMode.CREATE_OR_APPEND);
    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);
  nrtManagerReopenThread.start();
}
 
Example #7
Source File: ImmediateResultListenableFuture.java    From threadly with Mozilla Public License 2.0 5 votes vote down vote up
@Override
public ListenableFuture<T> resultCallback(Consumer<? super T> callback, Executor executor, 
                                          ListenerOptimizationStrategy optimize) {
  if (invokeCompletedDirectly(executor, optimize)) {
    callback.accept(result);
  } else {
    executor.execute(() -> callback.accept(result));
  }
  
  return this;
}
 
Example #8
Source File: Main.java    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 {
                    test(port);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
}
 
Example #9
Source File: MasterHooks.java    From flink with Apache License 2.0 5 votes vote down vote up
@Nullable
@Override
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(
			userClassLoader,
			() -> hook.triggerCheckpoint(checkpointId, timestamp, wrappedExecutor));
}
 
Example #10
Source File: AbstractReplicator.java    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
 */
@NonNull
public ListenerToken addDocumentReplicationListener(
    @Nullable Executor executor,
    @NonNull DocumentReplicationListener listener) {
    Preconditions.assertNotNull(listener, "listener");
    synchronized (lock) {
        setProgressLevel(ReplicatorProgressLevel.PER_DOCUMENT);
        final DocumentReplicationListenerToken token = new DocumentReplicationListenerToken(executor, listener);
        docEndedListenerTokens.add(token);
        return token;
    }
}
 
Example #11
Source File: ConnectivityStateManager.java    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) {
    stateChangeListener.runInExecutor();
  } else {
    listeners.add(stateChangeListener);
  }
}
 
Example #12
Source File: Scheduler.java    From caffeine with Apache License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings("NullAway")
public Future<?> schedule(Executor executor, Runnable command, long delay, TimeUnit unit) {
  requireNonNull(executor);
  requireNonNull(command);
  requireNonNull(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: StorageTask.java    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
 */
@NonNull
@Override
public StorageTask<ResultT> addOnProgressListener(
    @NonNull Executor executor, @NonNull OnProgressListener<? super ResultT> listener) {
  Preconditions.checkNotNull(listener);
  Preconditions.checkNotNull(executor);
  progressManager.addListener(null, executor, listener);
  return this;
}
 
Example #14
Source File: CompletableFuture.java    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: SettingsTests.java    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() {
        @Override
        public void run() { }
    };

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

            condition.open();
        }
    };

    Executor original = Settings.getExecutor();
    try {
        Settings.setExecutor(executor);
        Settings.getExecutor().execute(runnable);

        boolean success = condition.block(5000);
        assertTrue(success);
    } finally {
        Settings.setExecutor(original);
    }
}
 
Example #16
Source File: PathHandler.java    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) {
    Objects.requireNonNull(root);
    Objects.requireNonNull(executor);
    this.root = root.normalize();
    this.executor = executor;
    this.loader = ClassLoader.getSystemClassLoader();
}
 
Example #17
Source File: DnsNameResolverTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testExecutor_custom() throws Exception {
  final List<InetAddress> answer = createAddressList(2);
  final AtomicInteger executions = new AtomicInteger();

  NameResolver.Args args =
      NameResolver.Args.newBuilder()
          .setDefaultPort(81)
          .setProxyDetector(GrpcUtil.NOOP_PROXY_DETECTOR)
          .setSynchronizationContext(syncContext)
          .setServiceConfigParser(mock(ServiceConfigParser.class))
          .setChannelLogger(mock(ChannelLogger.class))
          .setOffloadExecutor(
              new Executor() {
                @Override
                public void execute(Runnable command) {
                  executions.incrementAndGet();
                  command.run();
                }
              })
          .build();

  DnsNameResolver resolver =
      newResolver("foo.googleapis.com", Stopwatch.createUnstarted(), false, args);
  AddressResolver mockResolver = mock(AddressResolver.class);
  when(mockResolver.resolveAddress(anyString())).thenReturn(answer);
  resolver.setAddressResolver(mockResolver);

  resolver.start(mockListener);
  assertEquals(0, fakeExecutor.runDueTasks());
  verify(mockListener).onResult(resultCaptor.capture());
  assertAnswerMatches(answer, 81, resultCaptor.getValue());
  assertEquals(0, fakeClock.numPendingTasks());

  resolver.shutdown();

  assertThat(fakeExecutorResource.createCount.get()).isEqualTo(0);
  assertThat(executions.get()).isEqualTo(1);
}
 
Example #18
Source File: DistributionManager.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
private Executor getSerialExecutor(InternalDistributedMember sender) {
   if (MULTI_SERIAL_EXECUTORS) {
     return this.serialQueuedExecutorPool.getThrottledSerialExecutor(sender);
   } else {
     return this.serialThread;
   }
}
 
Example #19
Source File: NettyConnectibleBuilder.java    From postgres-async-driver with Apache License 2.0 5 votes vote down vote up
private ProtocolStream newProtocolStream(Executor futuresExecutor) {
    return new NettyProtocolStream(
            group,
            new InetSocketAddress(properties.getHostname(), properties.getPort()),
            properties.getUseSsl(),
            Charset.forName(properties.getEncoding()),
            futuresExecutor
    );
}
 
Example #20
Source File: ConcurrentEvaluator.java    From jenetics with Apache License 2.0 5 votes vote down vote up
ConcurrentEvaluator(
	final Function<? super Genotype<G>, ? extends C> function,
	final Executor executor
) {
	_function = requireNonNull(function);
	_executor = requireNonNull(executor);
}
 
Example #21
Source File: Application.java    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.
 */
@Override
public Executor getAsyncExecutor() {
	executor = new ThreadPoolTaskExecutor();
	// Do not change the number of threads here
	executor.setCorePoolSize(1);
	// Do not change the number of threads here
	executor.setMaxPoolSize(1);
	executor.setQueueCapacity(100000);
	executor.setThreadNamePrefix("AsyncActionQueue-");
	executor.initialize();
	return executor;
}
 
Example #22
Source File: ThreadPools.java    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 {
        executor.execute(runnable);
    } catch (RejectedExecutionException e) {
        runnable.run();
    }
}
 
Example #23
Source File: BusyBeeExecutorWrapper.java    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: FutureUtilsTest.java    From Flink-CEPplus with Apache License 2.0 5 votes vote down vote up
@Test
public void testComposeAsyncIfNotDone() {
	testFutureContinuation((CompletableFuture<?> future, Executor executor) ->
		FutureUtils.thenComposeAsyncIfNotDone(
			future,
			executor,
			o -> null));
}
 
Example #25
Source File: CompletableFuture.java    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: ExecutionGraphBuilder.java    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(
		prior,
		jobGraph,
		jobManagerConfig,
		futureExecutor,
		ioExecutor,
		slotProvider,
		classLoader,
		recoveryFactory,
		rpcTimeout,
		restartStrategy,
		metrics,
		-1,
		blobWriter,
		allocationTimeout,
		log);
}
 
Example #27
Source File: TaskModel.java    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();
    model.addListDataListener(list);
    selectionModel.addListSelectionListener(list);
    this.eventExecutor = eventExecutor;
}
 
Example #28
Source File: PojoConfig.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Bean
Executor executor() {
  if (LOADING_MODE_BLOCKING.equals(loadingMode())) {
    return Runnable::run;
  }

  return Executors.newSingleThreadExecutor();
}
 
Example #29
Source File: JvmAuthTokenProvider.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
TokenChangeListenerWrapper(
    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: CompletableFuture.java    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;
}