Java Code Examples for java.util.concurrent.Executor

The following are top voted examples for showing how to use java.util.concurrent.Executor. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: simple-stack   File: Chats.java   View source code 6 votes vote down vote up
@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?") //
                    ))) //
    );
}
 
Example 2
Project: athena   File: ClusterCommunicationManager.java   View source code 6 votes vote down vote up
@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;
            }));
}
 
Example 3
Project: Hitalk   File: Task.java   View source code 6 votes vote down vote up
/**
 * 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);
}
 
Example 4
Project: googles-monorepo-demo   File: ExecutionListBenchmark.java   View source code 6 votes vote down vote up
@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;
    }
  };
}
 
Example 5
Project: openjdk-jdk10   File: ClientNotifForwarder.java   View source code 6 votes vote down vote up
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();
}
 
Example 6
Project: GitHub   File: DataSourcesTest.java   View source code 6 votes vote down vote up
@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();
}
 
Example 7
Project: BibliotecaPS   File: LoadBalancedConnectionProxy.java   View source code 6 votes vote down vote up
/**
 * 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();
}
 
Example 8
Project: neoscada   File: ScriptMonitor.java   View source code 6 votes vote down vote up
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 );
        }
    };
}
 
Example 9
Project: guava-mock   File: ExecutionListBenchmark.java   View source code 6 votes vote down vote up
@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;
    }
  };
}
 
Example 10
Project: incubator-netbeans   File: FileObjects.java   View source code 6 votes vote down vote up
@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);
}
 
Example 11
Project: jdk8u-jdk   File: ClientNotifForwarder.java   View source code 6 votes vote down vote up
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();
}
 
Example 12
Project: Nird2   File: TransportKeyManagerImplTest.java   View source code 6 votes vote down vote up
@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();
}
 
Example 13
Project: dremio-oss   File: DremioConnectionImpl.java   View source code 6 votes vote down vote up
@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." );
    }
  }
}
 
Example 14
Project: Nird2   File: TransportKeyManagerImplTest.java   View source code 6 votes vote down vote up
@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();
}
 
Example 15
Project: googles-monorepo-demo   File: MoreExecutorsTest.java   View source code 5 votes vote down vote up
public void testExecutors_nullCheck() throws Exception {
  new ClassSanityTester()
      .setDefault(RateLimiter.class, RateLimiter.create(1.0))
      .forAllPublicStaticMethods(MoreExecutors.class)
      .thatReturn(Executor.class)
      .testNulls();
}
 
Example 16
Project: GitHub   File: ErrorHandlingAdapter.java   View source code 5 votes vote down vote up
@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);
}
 
Example 17
Project: KUtils-master   File: AsyncExecutor.java   View source code 5 votes vote down vote up
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);
    }
}
 
Example 18
Project: spring-boot-oauth2-demo   File: AsyncConfig.java   View source code 5 votes vote down vote up
@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);
}
 
Example 19
Project: Nird2   File: PluginModule.java   View source code 5 votes vote down vote up
@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;
}
 
Example 20
Project: firebase-admin-java   File: TaskImpl.java   View source code 5 votes vote down vote up
@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;
}
 
Example 21
Project: lams   File: AsyncContextImpl.java   View source code 5 votes vote down vote up
private Executor asyncExecutor() {
    Executor executor = servletRequestContext.getDeployment().getAsyncExecutor();
    if (executor == null) {
        executor = servletRequestContext.getDeployment().getExecutor();
    }
    if (executor == null) {
        executor = exchange.getConnection().getWorker();
    }
    return executor;
}
 
Example 22
Project: Equella   File: MessageReceiver.java   View source code 5 votes vote down vote up
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;
}
 
Example 23
Project: Nird2   File: SyncSessionFactoryImpl.java   View source code 5 votes vote down vote up
@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;
}
 
Example 24
Project: Nird2   File: KeyAgreementModule.java   View source code 5 votes vote down vote up
@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);
}
 
Example 25
Project: tascalate-concurrent   File: CallbackRegistry.java   View source code 5 votes vote down vote up
@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;
}
 
Example 26
Project: Nird2   File: BlogControllerImpl.java   View source code 5 votes vote down vote up
@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;
}
 
Example 27
Project: little-promise   File: DefaultExecutors.java   View source code 5 votes vote down vote up
public static Executor newThread() {
    return new Executor() {
        @Override
        public void execute(Runnable runnable) {
            new Thread(runnable).start();
        }
    };
}
 
Example 28
Project: openjdk-jdk10   File: AsExecutor.java   View source code 5 votes vote down vote up
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");
}
 
Example 29
Project: Nird2   File: BlogControllerImpl.java   View source code 5 votes vote down vote up
@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;
}
 
Example 30
Project: Elasticsearch   File: TopRowUpstream.java   View source code 5 votes vote down vote up
public TopRowUpstream(Executor executor,
                      Runnable resumeRunnable,
                      Runnable repeatRunnable)  {
    this.executor = executor;
    this.resumeRunnable = resumeRunnable;
    this.repeatRunnable = repeatRunnable;
}
 
Example 31
Project: neoscada   File: ResponseManager.java   View source code 5 votes vote down vote up
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$
}
 
Example 32
Project: java-spring-cloud   File: ExecutorBeanPostProcessor.java   View source code 5 votes vote down vote up
@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();
}
 
Example 33
Project: tascalate-concurrent   File: Promises.java   View source code 5 votes vote down vote up
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);
}
 
Example 34
Project: dubbocloud   File: LimitedThreadPool.java   View source code 5 votes vote down vote up
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));
}
 
Example 35
Project: db-queue   File: QueueExecutionPool.java   View source code 5 votes vote down vote up
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;
}
 
Example 36
Project: openjdk-jdk10   File: MinimalFuture.java   View source code 5 votes vote down vote up
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;
}
 
Example 37
Project: spanner-jdbc   File: AbstractCloudSpannerConnectionTest.java   View source code 5 votes vote down vote up
@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);
}
 
Example 38
Project: Nird2   File: ModemImpl.java   View source code 5 votes vote down vote up
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];
}
 
Example 39
Project: hadoop   File: TestHttpServer.java   View source code 5 votes vote down vote up
/** 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();
}
 
Example 40
Project: util4j   File: AbstractCallBackCache.java   View source code 5 votes vote down vote up
/**
 * 手动指定超时执行器
 * @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;
}