Java Code Examples for java.util.concurrent.Executor
The following examples show how to use
java.util.concurrent.Executor. These examples are extracted from open source projects.
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 Project: incubator-retired-wave Source File: LucenePerUserWaveViewHandlerImpl.java License: Apache License 2.0 | 6 votes |
@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 2
Source Project: apollo-android Source File: CacheFirstFetcher.java License: MIT License | 6 votes |
@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 3
Source Project: hottub Source File: PathHandler.java License: GNU General Public License v2.0 | 6 votes |
/** * 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 Project: crate Source File: MockTcpTransport.java License: Apache License 2.0 | 6 votes |
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 5
Source Project: ignite Source File: JdbcThinConnection.java License: Apache License 2.0 | 6 votes |
/** {@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 6
Source Project: armeria Source File: AbstractHttpFile.java License: Apache License 2.0 | 6 votes |
@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 7
Source Project: jdk8u60 Source File: PathHandler.java License: GNU General Public License v2.0 | 5 votes |
/** * @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 8
Source Project: firebase-android-sdk Source File: StorageTask.java License: Apache License 2.0 | 5 votes |
/** * 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 9
Source Project: caffeine Source File: Scheduler.java License: Apache License 2.0 | 5 votes |
@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 10
Source Project: flink Source File: MasterHooks.java License: Apache License 2.0 | 5 votes |
@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 11
Source Project: gemfirexd-oss Source File: DistributionManager.java License: Apache License 2.0 | 5 votes |
private Executor getSerialExecutor(InternalDistributedMember sender) { if (MULTI_SERIAL_EXECUTORS) { return this.serialQueuedExecutorPool.getThrottledSerialExecutor(sender); } else { return this.serialThread; } }
Example 12
Source Project: grpc-java Source File: DnsNameResolverTest.java License: Apache License 2.0 | 5 votes |
@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 13
Source Project: jenetics Source File: ConcurrentEvaluator.java License: Apache License 2.0 | 5 votes |
ConcurrentEvaluator( final Function<? super Genotype<G>, ? extends C> function, final Executor executor ) { _function = requireNonNull(function); _executor = requireNonNull(executor); }
Example 14
Source Project: difido-reports Source File: Application.java License: Apache License 2.0 | 5 votes |
/** * 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 15
Source Project: openjdk-8-source Source File: CompletableFuture.java License: GNU General Public License v2.0 | 5 votes |
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 16
Source Project: couchbase-lite-java Source File: AbstractReplicator.java License: Apache License 2.0 | 5 votes |
/** * 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 17
Source Project: grpc-nebula-java Source File: ConnectivityStateManager.java License: Apache License 2.0 | 5 votes |
/** * 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 18
Source Project: dubbo-2.6.5 Source File: Main.java License: Apache License 2.0 | 5 votes |
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 19
Source Project: FacebookImageShareIntent Source File: SettingsTests.java License: MIT License | 5 votes |
@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 20
Source Project: Flink-CEPplus Source File: ExecutionGraphBuilder.java License: Apache License 2.0 | 5 votes |
/** * 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 21
Source Project: netbeans Source File: TaskModel.java License: Apache License 2.0 | 5 votes |
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 22
Source Project: servicecomb-java-chassis Source File: PojoConfig.java License: Apache License 2.0 | 5 votes |
@Bean Executor executor() { if (LOADING_MODE_BLOCKING.equals(loadingMode())) { return Runnable::run; } return Executors.newSingleThreadExecutor(); }
Example 23
Source Project: Flink-CEPplus Source File: FutureUtilsTest.java License: Apache License 2.0 | 5 votes |
@Test public void testComposeAsyncIfNotDone() { testFutureContinuation((CompletableFuture<?> future, Executor executor) -> FutureUtils.thenComposeAsyncIfNotDone( future, executor, o -> null)); }
Example 24
Source Project: busybee Source File: BusyBeeExecutorWrapper.java License: Apache License 2.0 | 5 votes |
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 25
Source Project: crate Source File: ThreadPools.java License: Apache License 2.0 | 5 votes |
/** * 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 26
Source Project: postgres-async-driver Source File: NettyConnectibleBuilder.java License: Apache License 2.0 | 5 votes |
private ProtocolStream newProtocolStream(Executor futuresExecutor) { return new NettyProtocolStream( group, new InetSocketAddress(properties.getHostname(), properties.getPort()), properties.getUseSsl(), Charset.forName(properties.getEncoding()), futuresExecutor ); }
Example 27
Source Project: firebase-admin-java Source File: JvmAuthTokenProvider.java License: Apache License 2.0 | 5 votes |
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 28
Source Project: threadly Source File: ImmediateResultListenableFuture.java License: Mozilla Public License 2.0 | 5 votes |
@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 29
Source Project: openjdk-8 Source File: CompletableFuture.java License: GNU General Public License v2.0 | 5 votes |
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 30
Source Project: curator Source File: MappingListenerManager.java License: Apache License 2.0 | 4 votes |
@Override public void addListener(K listener, Executor executor) { V mapped = mapper.apply(listener); listeners.put(listener, new ListenerEntry<>(mapped, executor)); }