类java.util.concurrent.Executor源码实例Demo

下面列出了怎么用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();
}
 
源代码2 项目: apollo-android   文件: CacheFirstFetcher.java
@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);
    }
  });
}
 
源代码3 项目: hottub   文件: PathHandler.java
/**
 * 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);
        }
    }
}
 
源代码4 项目: crate   文件: MockTcpTransport.java
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));
            }
        }
    });
}
 
源代码5 项目: ignite   文件: JdbcThinConnection.java
/** {@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);
}
 
源代码6 项目: armeria   文件: AbstractHttpFile.java
@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);
    }
}
 
源代码7 项目: jdk8u60   文件: PathHandler.java
/**
 * @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();
}
 
源代码8 项目: firebase-android-sdk   文件: StorageTask.java
/**
 * 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;
}
 
源代码9 项目: caffeine   文件: Scheduler.java
@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);
  }
}
 
源代码10 项目: flink   文件: MasterHooks.java
@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));
}
 
源代码11 项目: gemfirexd-oss   文件: DistributionManager.java
private Executor getSerialExecutor(InternalDistributedMember sender) {
   if (MULTI_SERIAL_EXECUTORS) {
     return this.serialQueuedExecutorPool.getThrottledSerialExecutor(sender);
   } else {
     return this.serialThread;
   }
}
 
源代码12 项目: grpc-java   文件: DnsNameResolverTest.java
@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);
}
 
源代码13 项目: jenetics   文件: ConcurrentEvaluator.java
ConcurrentEvaluator(
	final Function<? super Genotype<G>, ? extends C> function,
	final Executor executor
) {
	_function = requireNonNull(function);
	_executor = requireNonNull(executor);
}
 
源代码14 项目: difido-reports   文件: Application.java
/**
 * 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;
}
 
源代码15 项目: openjdk-8-source   文件: CompletableFuture.java
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);
}
 
源代码16 项目: couchbase-lite-java   文件: AbstractReplicator.java
/**
 * 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);
  }
}
 
源代码18 项目: dubbo-2.6.5   文件: Main.java
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();
                }
            }
        });
}
 
源代码19 项目: FacebookImageShareIntent   文件: SettingsTests.java
@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);
    }
}
 
源代码20 项目: Flink-CEPplus   文件: ExecutionGraphBuilder.java
/**
 * 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);
}
 
源代码21 项目: netbeans   文件: TaskModel.java
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;
}
 
源代码22 项目: servicecomb-java-chassis   文件: PojoConfig.java
@Bean
Executor executor() {
  if (LOADING_MODE_BLOCKING.equals(loadingMode())) {
    return Runnable::run;
  }

  return Executors.newSingleThreadExecutor();
}
 
源代码23 项目: Flink-CEPplus   文件: FutureUtilsTest.java
@Test
public void testComposeAsyncIfNotDone() {
	testFutureContinuation((CompletableFuture<?> future, Executor executor) ->
		FutureUtils.thenComposeAsyncIfNotDone(
			future,
			executor,
			o -> null));
}
 
源代码24 项目: busybee   文件: BusyBeeExecutorWrapper.java
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);
    }
}
 
源代码25 项目: crate   文件: ThreadPools.java
/**
 * 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
    );
}
 
源代码27 项目: firebase-admin-java   文件: JvmAuthTokenProvider.java
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;
}
 
源代码28 项目: threadly   文件: ImmediateResultListenableFuture.java
@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;
}
 
源代码29 项目: openjdk-8   文件: CompletableFuture.java
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;
}
 
源代码30 项目: curator   文件: MappingListenerManager.java
@Override
public void addListener(K listener, Executor executor)
{
    V mapped = mapper.apply(listener);
    listeners.put(listener, new ListenerEntry<>(mapped, executor));
}
 
 类所在包
 同包方法