@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?") // ))) // ); }
@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; })); }
/** * 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); }
@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; } }; }
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(); }
@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(); }
/** * 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(); }
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 ); } }; }
@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; } }; }
@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); }
@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(); }
@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." ); } } }
public void testExecutors_nullCheck() throws Exception { new ClassSanityTester() .setDefault(RateLimiter.class, RateLimiter.create(1.0)) .forAllPublicStaticMethods(MoreExecutors.class) .thatReturn(Executor.class) .testNulls(); }
@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); }
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); } }
@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); }
@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; }
@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; }
private Executor asyncExecutor() { Executor executor = servletRequestContext.getDeployment().getAsyncExecutor(); if (executor == null) { executor = servletRequestContext.getDeployment().getExecutor(); } if (executor == null) { executor = exchange.getConnection().getWorker(); } return executor; }
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; }
@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; }
@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); }
@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; }
@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; }
public static Executor newThread() { return new Executor() { @Override public void execute(Runnable runnable) { new Thread(runnable).start(); } }; }
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"); }
public TopRowUpstream(Executor executor, Runnable resumeRunnable, Runnable repeatRunnable) { this.executor = executor; this.resumeRunnable = resumeRunnable; this.repeatRunnable = repeatRunnable; }
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$ }
@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(); }
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); }
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)); }
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; }
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; }
@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); }
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]; }
/** 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(); }
/** * 手动指定超时执行器 * @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; }