下面列出了怎么用java.util.concurrent.Executor的API类实例代码及写法,或者点击链接到github查看源代码。
@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();
}
@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);
}
});
}
/**
* 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);
}
}
}
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));
}
}
});
}
/** {@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);
}
@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);
}
}
/**
* @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();
}
/**
* 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;
}
@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);
}
}
@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));
}
private Executor getSerialExecutor(InternalDistributedMember sender) {
if (MULTI_SERIAL_EXECUTORS) {
return this.serialQueuedExecutorPool.getThrottledSerialExecutor(sender);
} else {
return this.serialThread;
}
}
@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);
}
ConcurrentEvaluator(
final Function<? super Genotype<G>, ? extends C> function,
final Executor executor
) {
_function = requireNonNull(function);
_executor = requireNonNull(executor);
}
/**
* 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;
}
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);
}
/**
* 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;
}
}
/**
* 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);
}
}
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();
}
}
});
}
@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);
}
}
/**
* 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);
}
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;
}
@Bean
Executor executor() {
if (LOADING_MODE_BLOCKING.equals(loadingMode())) {
return Runnable::run;
}
return Executors.newSingleThreadExecutor();
}
@Test
public void testComposeAsyncIfNotDone() {
testFutureContinuation((CompletableFuture<?> future, Executor executor) ->
FutureUtils.thenComposeAsyncIfNotDone(
future,
executor,
o -> null));
}
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);
}
}
/**
* 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();
}
}
private ProtocolStream newProtocolStream(Executor futuresExecutor) {
return new NettyProtocolStream(
group,
new InetSocketAddress(properties.getHostname(), properties.getPort()),
properties.getUseSsl(),
Charset.forName(properties.getEncoding()),
futuresExecutor
);
}
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;
}
@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;
}
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;
}
@Override
public void addListener(K listener, Executor executor)
{
V mapped = mapper.apply(listener);
listeners.put(listener, new ListenerEntry<>(mapped, executor));
}