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

项目:simple-stack    文件:Chats.java   
@Inject
Chats(Executor messagePollThread, QuoteService service) {
    this.messagePollThread = messagePollThread;
    this.service = service;

    User alex = new User(0, "Alex");
    User chris = new User(1, "Chris");

    friends = asList(alex, chris);

    all = Collections.unmodifiableList(asList(//
            new Chat(this, 0, asList(alex, chris), //
                    asList(new Message(me, "What's up?"), //
                            new Message(alex, "Not much."), //
                            new Message(chris, "Wanna hang out?"), //
                            new Message(me, "Sure."), //
                            new Message(alex, "Let's do it.") //
                    )), //
            new Chat(this, 1, asList(chris), //
                    asList(new Message(me, "You there bro?") //
                    ))) //
    );
}
项目:athena    文件:ClusterCommunicationManager.java   
@Override
public <M, R> void addSubscriber(MessageSubject subject,
        Function<byte[], M> decoder,
        Function<M, R> handler,
        Function<R, byte[]> encoder,
        Executor executor) {
    checkPermission(CLUSTER_WRITE);
    messagingService.registerHandler(subject.value(),
            new InternalMessageResponder<M, R>(decoder, encoder, m -> {
                CompletableFuture<R> responseFuture = new CompletableFuture<>();
                executor.execute(() -> {
                    try {
                        responseFuture.complete(handler.apply(m));
                    } catch (Exception e) {
                        responseFuture.completeExceptionally(e);
                    }
                });
                return responseFuture;
            }));
}
项目:Hitalk    文件:Task.java   
/**
 * Continues a task with the equivalent of a Task-based while loop, where the body of the loop is
 * a task continuation.
 */
public Task<Void> continueWhile(final Callable<Boolean> predicate,
    final Continuation<Void, Task<Void>> continuation, final Executor executor,
    final CancellationToken ct) {
  final Capture<Continuation<Void, Task<Void>>> predicateContinuation =
      new Capture<>();
  predicateContinuation.set(new Continuation<Void, Task<Void>>() {
    @Override
    public Task<Void> then(Task<Void> task) throws Exception {
      if (ct != null && ct.isCancellationRequested()) {
        return Task.cancelled();
      }

      if (predicate.call()) {
        return Task.<Void> forResult(null).onSuccessTask(continuation, executor)
            .onSuccessTask(predicateContinuation.get(), executor);
      }
      return Task.forResult(null);
    }
  });
  return makeVoid().continueWithTask(predicateContinuation.get(), executor);
}
项目:googles-monorepo-demo    文件:ExecutionListBenchmark.java   
@Override ExecutionListWrapper newExecutionList() {
  return new ExecutionListWrapper() {
    final ExecutionListCAS list = new ExecutionListCAS();
    @Override public void add(Runnable runnable, Executor executor) {
      list.add(runnable, executor);
    }

    @Override public void execute() {
      list.execute();
    }

    @Override public Object getImpl() {
      return list;
    }
  };
}
项目:openjdk-jdk10    文件:ClientNotifForwarder.java   
public ClientNotifForwarder(ClassLoader defaultClassLoader, Map<String, ?> env) {
    maxNotifications = EnvHelp.getMaxFetchNotifNumber(env);
    timeout = EnvHelp.getFetchTimeout(env);

    /* You can supply an Executor in which the remote call to
       fetchNotifications will be made.  The Executor's execute
       method reschedules another task, so you must not use
       an Executor that executes tasks in the caller's thread.  */
    Executor ex = (Executor)
        env.get("jmx.remote.x.fetch.notifications.executor");
    if (ex == null)
        ex = new LinearExecutor();
    else if (logger.traceOn())
        logger.trace("ClientNotifForwarder", "executor is " + ex);

    this.defaultClassLoader = defaultClassLoader;
    this.executor = ex;
    this.acc = AccessController.getContext();
}
项目:GitHub    文件:DataSourcesTest.java   
@Test
public void testWaitForFinalResult_whenOnlyIntermediateResult_thenNoUpdate() throws Throwable {
  when(mDataSource.isFinished()).thenReturn(false);
  when(mDataSource.getResult()).thenReturn(mIntermediateResult);

  doAnswer(new Answer<Void>() {
    @Override
    public Void answer(InvocationOnMock invocation) throws Throwable {
      final Object[] args = invocation.getArguments();
      DataSubscriber dataSubscriber = (DataSubscriber) args[0];
      dataSubscriber.onNewResult(mDataSource);
      return null;
    }
  }).when(mDataSource).subscribe(any(DataSubscriber.class), any(Executor.class));

  // the mocked one falls through, but the real one waits with the countdown latch for isFinished
  final Object actual = DataSources.waitForFinalResult(mDataSource);
  assertEquals(null, actual);

  verify(mCountDownLatch, times(1)).await();
  verify(mCountDownLatch, never()).countDown();
}
项目:BibliotecaPS    文件:LoadBalancedConnectionProxy.java   
/**
 * Aborts all live connections, using the provided Executor.
 */
@Override
synchronized void doAbort(Executor executor) {
    // close all underlying connections
    for (MySQLConnection c : this.liveConnections.values()) {
        try {
            c.abort(executor);
        } catch (SQLException e) {
        }
    }

    if (!this.isClosed) {
        this.balancer.destroy();
        if (this.connectionGroup != null) {
            this.connectionGroup.closeConnectionProxy(this);
        }
    }

    this.liveConnections.clear();
    this.connectionsToHostsMap.clear();
}
项目:neoscada    文件:ScriptMonitor.java   
public ScriptMonitor ( final String id, final String factoryId, final Executor executor, final BundleContext context, final Interner<String> stringInterner, final EventProcessor eventProcessor, final ObjectPoolTracker<DataSource> dataSourcePoolTracker, final ObjectPoolTracker<MasterItem> masterItemPoolTracker, final ServiceTracker<ConfigurationAdministrator, ConfigurationAdministrator> caTracker )
{
    super ( id, factoryId, executor, context, stringInterner, eventProcessor );
    this.executor = executor;

    this.prefix = stringInterner.intern ( factoryId + ". " + id ); //$NON-NLS-1$

    this.classLoader = getClass ().getClassLoader ();

    this.monitorStateInjector = new MonitorStateInjector ( stringInterner );
    this.monitorStateInjector.setPrefix ( this.prefix );

    this.handler = new InjectMasterHandler ( id, masterItemPoolTracker, 0, caTracker, this.prefix, factoryId );
    this.listener = new MultiDataSourceListener ( dataSourcePoolTracker ) {

        @Override
        protected void handleChange ( final Map<String, DataSourceHandler> sources )
        {
            ScriptMonitor.this.handleChange ( sources );
        }
    };
}
项目:guava-mock    文件:ExecutionListBenchmark.java   
@Override ExecutionListWrapper newExecutionList() {
  return new ExecutionListWrapper() {
    final AbstractFuture<?> future = new AbstractFuture<Object>() {};
    @Override public void add(Runnable runnable, Executor executor) {
      future.addListener(runnable, executor);
    }

    @Override public void execute() {
      future.set(null);
    }

    @Override public Object getImpl() {
      return future;
    }
  };
}
项目:incubator-netbeans    文件:FileObjects.java   
@NonNull
public static PrefetchableJavaFileObject asyncWriteFileObject(
    @NonNull final File file,
    @NonNull final File root,
    @NullAllowed JavaFileFilterImplementation filter,
    @NullAllowed Charset encoding,
    @NonNull final Executor pool,
    @NonNull final CompletionHandler<Void,Void> done) {
    final String[] pkgNamePair = getFolderAndBaseName(getRelativePath(root,file),File.separatorChar);
    return new AsyncWriteFileObject(
        file,
        convertFolder2Package(pkgNamePair[0], File.separatorChar),
        pkgNamePair[1],
        filter,
        encoding,
        pool,
        done);
}
项目:jdk8u-jdk    文件:ClientNotifForwarder.java   
public ClientNotifForwarder(ClassLoader defaultClassLoader, Map<String, ?> env) {
    maxNotifications = EnvHelp.getMaxFetchNotifNumber(env);
    timeout = EnvHelp.getFetchTimeout(env);

    /* You can supply an Executor in which the remote call to
       fetchNotifications will be made.  The Executor's execute
       method reschedules another task, so you must not use
       an Executor that executes tasks in the caller's thread.  */
    Executor ex = (Executor)
        env.get("jmx.remote.x.fetch.notifications.executor");
    if (ex == null)
        ex = new LinearExecutor();
    else if (logger.traceOn())
        logger.trace("ClientNotifForwarder", "executor is " + ex);

    this.defaultClassLoader = defaultClassLoader;
    this.executor = ex;
    this.acc = AccessController.getContext();
}
项目:Nird2    文件:TransportKeyManagerImplTest.java   
@Test
public void testOutgoingStreamContextIsNullIfContactIsNotFound()
        throws Exception {
    Mockery context = new Mockery();
    final DatabaseComponent db = context.mock(DatabaseComponent.class);
    final CryptoComponent crypto = context.mock(CryptoComponent.class);
    final Executor dbExecutor = context.mock(Executor.class);
    final ScheduledExecutorService scheduler =
            context.mock(ScheduledExecutorService.class);
    final Clock clock = context.mock(Clock.class);

    final Transaction txn = new Transaction(null, false);

    TransportKeyManager
            transportKeyManager = new TransportKeyManagerImpl(db,
            crypto, dbExecutor, scheduler, clock, transportId, maxLatency);
    assertNull(transportKeyManager.getStreamContext(txn, contactId));

    context.assertIsSatisfied();
}
项目:dremio-oss    文件:DremioConnectionImpl.java   
@Override
public void setNetworkTimeout( Executor executor, int milliseconds )
    throws AlreadyClosedSqlException,
           JdbcApiSqlException,
           SQLFeatureNotSupportedException,
           SQLException {
  throwIfClosed();
  if ( null == executor ) {
    throw new InvalidParameterSqlException(
        "Invalid (null) \"executor\" parameter to setNetworkTimeout(...)" );
  }
  else if ( milliseconds < 0 ) {
    throw new InvalidParameterSqlException(
        "Invalid (negative) \"milliseconds\" parameter to"
        + " setNetworkTimeout(...) (" + milliseconds + ")" );
  }
  else {
    if ( 0 != milliseconds ) {
      throw new SQLFeatureNotSupportedException(
          "Setting network timeout is not supported." );
    }
  }
}
项目:Nird2    文件:TransportKeyManagerImplTest.java   
@Test
public void testOutgoingStreamContextIsNullIfContactIsNotFound()
        throws Exception {
    Mockery context = new Mockery();
    final DatabaseComponent db = context.mock(DatabaseComponent.class);
    final CryptoComponent crypto = context.mock(CryptoComponent.class);
    final Executor dbExecutor = context.mock(Executor.class);
    final ScheduledExecutorService scheduler =
            context.mock(ScheduledExecutorService.class);
    final Clock clock = context.mock(Clock.class);

    final Transaction txn = new Transaction(null, false);

    TransportKeyManager
            transportKeyManager = new TransportKeyManagerImpl(db,
            crypto, dbExecutor, scheduler, clock, transportId, maxLatency);
    assertNull(transportKeyManager.getStreamContext(txn, contactId));

    context.assertIsSatisfied();
}
项目:googles-monorepo-demo    文件:MoreExecutorsTest.java   
public void testExecutors_nullCheck() throws Exception {
  new ClassSanityTester()
      .setDefault(RateLimiter.class, RateLimiter.create(1.0))
      .forAllPublicStaticMethods(MoreExecutors.class)
      .thatReturn(Executor.class)
      .testNulls();
}
项目:GitHub    文件:ErrorHandlingAdapter.java   
@Override public CallAdapter<?, ?> get(Type returnType, Annotation[] annotations,
    Retrofit retrofit) {
  if (getRawType(returnType) != MyCall.class) {
    return null;
  }
  if (!(returnType instanceof ParameterizedType)) {
    throw new IllegalStateException(
        "MyCall must have generic type (e.g., MyCall<ResponseBody>)");
  }
  Type responseType = getParameterUpperBound(0, (ParameterizedType) returnType);
  Executor callbackExecutor = retrofit.callbackExecutor();
  return new ErrorHandlingCallAdapter<>(responseType, callbackExecutor);
}
项目:KUtils-master    文件:AsyncExecutor.java   
private AsyncExecutor(Executor threadPool, EventBus eventBus, Class<?> failureEventType, Object scope) {
    this.threadPool = threadPool;
    this.eventBus = eventBus;
    this.scope = scope;
    try {
        failureEventConstructor = failureEventType.getConstructor(Throwable.class);
    } catch (NoSuchMethodException e) {
        throw new RuntimeException(
                "Failure event class must have a constructor with one parameter of type Throwable", e);
    }
}
项目:spring-boot-oauth2-demo    文件:AsyncConfig.java   
@Override
@Bean(name = "taskExecutor")
public Executor getAsyncExecutor() {
    log.debug("Creating Async Task Executor");
    ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
    executor.setCorePoolSize(asyncProperties.getCorePoolSize());
    executor.setMaxPoolSize(asyncProperties.getMaxPoolSize());
    executor.setQueueCapacity(asyncProperties.getQueueCapacity());
    executor.setThreadNamePrefix(asyncProperties.getNamePrefix());
    return new ExceptionHandlingAsyncTaskExecutor(executor);
}
项目:Nird2    文件:PluginModule.java   
@Provides
@Singleton
Poller providePoller(@IoExecutor Executor ioExecutor,
        @Scheduler ScheduledExecutorService scheduler,
        ConnectionManager connectionManager,
        ConnectionRegistry connectionRegistry, PluginManager pluginManager,
        SecureRandom random, Clock clock, EventBus eventBus) {
    Poller poller = new Poller(ioExecutor, scheduler, connectionManager,
            connectionRegistry, pluginManager, random, clock);
    eventBus.addListener(poller);
    return poller;
}
项目:firebase-admin-java    文件:TaskImpl.java   
@NonNull
@Override
public <R> Task<R> continueWithTask(
    @NonNull Executor executor, @NonNull Continuation<T, Task<R>> continuation) {
  TaskImpl<R> continuationTask = new TaskImpl<>();
  listenerQueue.add(
      new ContinueWithTaskCompletionListener<>(executor, continuation, continuationTask));
  flushIfComplete();
  return continuationTask;
}
项目:lams    文件:AsyncContextImpl.java   
private Executor asyncExecutor() {
    Executor executor = servletRequestContext.getDeployment().getAsyncExecutor();
    if (executor == null) {
        executor = servletRequestContext.getDeployment().getExecutor();
    }
    if (executor == null) {
        executor = exchange.getConnection().getWorker();
    }
    return executor;
}
项目:Equella    文件:MessageReceiver.java   
public MessageReceiver(String host, int port, String myId, String senderId, List<ClusterMessageHandler> handlers,
    Executor executor)
{
    this.host = host;
    this.port = port;
    this.myId = myId;
    this.senderId = senderId;
    this.handlers = handlers;
    this.executor = executor;
}
项目:Nird2    文件:SyncSessionFactoryImpl.java   
@Inject
SyncSessionFactoryImpl(DatabaseComponent db,
        @DatabaseExecutor Executor dbExecutor, EventBus eventBus,
        Clock clock, RecordReaderFactory recordReaderFactory,
        RecordWriterFactory recordWriterFactory) {
    this.db = db;
    this.dbExecutor = dbExecutor;
    this.eventBus = eventBus;
    this.clock = clock;
    this.recordReaderFactory = recordReaderFactory;
    this.recordWriterFactory = recordWriterFactory;
}
项目:Nird2    文件:KeyAgreementModule.java   
@Provides
@Singleton
KeyAgreementTaskFactory provideKeyAgreementTaskFactory(Clock clock,
        CryptoComponent crypto, EventBus eventBus,
        @IoExecutor Executor ioExecutor, PayloadEncoder payloadEncoder,
        PluginManager pluginManager) {
    return new KeyAgreementTaskFactoryImpl(clock, crypto, eventBus,
            ioExecutor, payloadEncoder, pluginManager);
}
项目:tascalate-concurrent    文件:CallbackRegistry.java   
@Override
protected State<S> addCallbacks(Function<? super Callable<?>, ? extends Runnable> targetSetup,
                                Function<? super S, ?> successCallback, 
                                Function<Throwable, ?> failureCallback, 
                                Executor executor) {

    callbacks.add(new CallbackHolder<>(targetSetup, successCallback, failureCallback, executor));
    return this;
}
项目:Nird2    文件:BlogControllerImpl.java   
@Inject
BlogControllerImpl(@DatabaseExecutor Executor dbExecutor,
        LifecycleManager lifecycleManager, EventBus eventBus,
        AndroidNotificationManager notificationManager,
        IdentityManager identityManager, BlogManager blogManager,
        BlogSharingManager blogSharingManager) {
    super(dbExecutor, lifecycleManager, eventBus, notificationManager,
            identityManager, blogManager);
    this.blogSharingManager = blogSharingManager;
}
项目:little-promise    文件:DefaultExecutors.java   
public static Executor newThread() {
    return new Executor() {
        @Override
        public void execute(Runnable runnable) {
            new Thread(runnable).start();
        }
    };
}
项目:openjdk-jdk10    文件:AsExecutor.java   
static void testAttackingTask(AsynchronousChannelGroup group) throws Exception {
    Executor executor = (Executor)group;
    Attack task = new Attack();
    executor.execute(task);
    task.waitUntilDone();
    if (!task.failedDueToSecurityException())
        throw new RuntimeException("SecurityException expected");
}
项目:Nird2    文件:BlogControllerImpl.java   
@Inject
BlogControllerImpl(@DatabaseExecutor Executor dbExecutor,
        LifecycleManager lifecycleManager, EventBus eventBus,
        AndroidNotificationManager notificationManager,
        IdentityManager identityManager, BlogManager blogManager,
        BlogSharingManager blogSharingManager) {
    super(dbExecutor, lifecycleManager, eventBus, notificationManager,
            identityManager, blogManager);
    this.blogSharingManager = blogSharingManager;
}
项目:Elasticsearch    文件:TopRowUpstream.java   
public TopRowUpstream(Executor executor,
                      Runnable resumeRunnable,
                      Runnable repeatRunnable)  {
    this.executor = executor;
    this.resumeRunnable = resumeRunnable;
    this.repeatRunnable = repeatRunnable;
}
项目:neoscada    文件:ResponseManager.java   
public ResponseManager ( final StatisticsImpl statistics, final MessageSender messageSender, final Executor executor )
{
    this.statistics = statistics;
    this.messageSender = messageSender;
    this.executor = executor;

    this.statistics.setLabel ( STATS_OPEN_REQUESTS, "Open requests" ); //$NON-NLS-1$
}
项目:java-spring-cloud    文件:ExecutorBeanPostProcessor.java   
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
  Executor tracedExecutor = tracedExecutor(tracer, delegate);
  Method methodOnTracedBean = getMethod(invocation, tracedExecutor);
  if (methodOnTracedBean != null) {
    return methodOnTracedBean.invoke(tracedExecutor, invocation.getArguments());
  }
  return invocation.proceed();
}
项目:tascalate-concurrent    文件:Promises.java   
public static <T> Promise<T> poll(Callable<? extends T> codeBlock, Executor executor, RetryPolicy retryPolicy) {
    Promise<ObjectRef<T>> wrappedResult = pollOptional(
        () -> Optional.of(new ObjectRef<T>( codeBlock.call() )), 
        executor, retryPolicy
    );
    return wrappedResult.dependent().thenApply(ObjectRef::dereference, true);
}
项目:dubbocloud    文件:LimitedThreadPool.java   
public Executor getExecutor(URL url) {
    String name = url.getParameter(Constants.THREAD_NAME_KEY, Constants.DEFAULT_THREAD_NAME);
    int cores = url.getParameter(Constants.CORE_THREADS_KEY, Constants.DEFAULT_CORE_THREADS);
    int threads = url.getParameter(Constants.THREADS_KEY, Constants.DEFAULT_THREADS);
    int queues = url.getParameter(Constants.QUEUES_KEY, Constants.DEFAULT_QUEUES);
    return new ThreadPoolExecutor(cores, threads, Long.MAX_VALUE, TimeUnit.MILLISECONDS, 
            queues == 0 ? new SynchronousQueue<Runnable>() : 
                (queues < 0 ? new LinkedBlockingQueue<Runnable>() 
                        : new LinkedBlockingQueue<Runnable>(queues)),
            new NamedThreadFactory(name, true), new AbortPolicyWithReport(name, url));
}
项目:db-queue    文件:QueueExecutionPool.java   
private ShardPoolInstance(QueueConsumer queueConsumer, QueueDao queueDao, TaskLifecycleListener taskListener,
                          ThreadLifecycleListener threadListener, Executor externalExecutor) {
    this.queueConsumer = queueConsumer;
    this.queueDao = queueDao;
    this.taskListener = taskListener;
    this.threadListener = threadListener;
    this.externalExecutor = externalExecutor;
}
项目:openjdk-jdk10    文件:MinimalFuture.java   
public static <U> CompletableFuture<U> supply(ExceptionalSupplier<U> supplier, Executor executor) {
    CompletableFuture<U> cf = new MinimalFuture<>();
    cf.completeAsync( () -> {
        try {
            return supplier.get();
        } catch (Throwable ex) {
            throw new CompletionException(ex);
        }
    }, executor);
    return cf;
}
项目:spanner-jdbc    文件:AbstractCloudSpannerConnectionTest.java   
@Test
public void testSetNetworkTimeout() throws Exception
{
    thrown.expect(SQLFeatureNotSupportedException.class);
    AbstractCloudSpannerConnection testSubject;
    Executor executor = null;
    int milliseconds = 0;

    // default test
    testSubject = createTestSubject();
    testSubject.setNetworkTimeout(executor, milliseconds);
}
项目:Nird2    文件:ModemImpl.java   
ModemImpl(Executor ioExecutor, ReliabilityLayerFactory reliabilityFactory,
        Clock clock, Callback callback, SerialPort port) {
    this.ioExecutor = ioExecutor;
    this.reliabilityFactory = reliabilityFactory;
    this.clock = clock;
    this.callback = callback;
    this.port = port;
    stateChange = new Semaphore(1);
    line = new byte[MAX_LINE_LENGTH];
}
项目:hadoop    文件:TestHttpServer.java   
/** Test the maximum number of threads cannot be exceeded. */
@Test public void testMaxThreads() throws Exception {
  int clientThreads = MAX_THREADS * 10;
  Executor executor = Executors.newFixedThreadPool(clientThreads);
  // Run many clients to make server reach its maximum number of threads
  final CountDownLatch ready = new CountDownLatch(clientThreads);
  final CountDownLatch start = new CountDownLatch(1);
  for (int i = 0; i < clientThreads; i++) {
    executor.execute(new Runnable() {
      @Override
      public void run() {
        ready.countDown();
        try {
          start.await();
          assertEquals("a:b\nc:d\n",
                       readOutput(new URL(baseUrl, "/echo?a=b&c=d")));
          int serverThreads = server.webServer.getThreadPool().getThreads();
          assertTrue("More threads are started than expected, Server Threads count: "
                  + serverThreads, serverThreads <= MAX_THREADS);
          System.out.println("Number of threads = " + serverThreads +
              " which is less or equal than the max = " + MAX_THREADS);
        } catch (Exception e) {
          // do nothing
        }
      }
    });
  }
  // Start the client threads when they are all ready
  ready.await();
  start.countDown();
}
项目:util4j    文件:AbstractCallBackCache.java   
/**
 * 手动指定超时执行器
 * @param callBack
 * @param timeOutExecutor
 * @return
 */
public KEY put(CallBack<TYPE> callBack,long timeOut,final Executor timeOutExecutor)
{
    Objects.requireNonNull(callBack);
    Objects.requireNonNull(timeOutExecutor);
    KEY ck=nextCallKey();
    if(timeOut<=0)
    {
        timeOut=CallBack.DEFAULT_TIMEOUT;
    }
    EventListener<KEY,CallBack<TYPE>> listener=new EventListener<KEY,CallBack<TYPE>>(){
        @Override
        public void removed(KEY key, CallBack<TYPE> value, boolean expire) {
            if(expire)
            {
                timeOutExecutor.execute(new Runnable() {
                    @Override
                    public void run() {
                        value.call(true);
                    }
                });
            }
        }
    };
    callBacks.put(ck, callBack, timeOut,listener);
    return ck;
}