本文整理匯總了Java中java.util.concurrent.CompletableFuture.runAsync方法的典型用法代碼示例。如果您正苦於以下問題:Java CompletableFuture.runAsync方法的具體用法?Java CompletableFuture.runAsync怎麽用?Java CompletableFuture.runAsync使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類java.util.concurrent.CompletableFuture
的用法示例。
在下文中一共展示了CompletableFuture.runAsync方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: testOnNextNotReadyThenCancelled
import java.util.concurrent.CompletableFuture; //導入方法依賴的package包/類
@Test
public void testOnNextNotReadyThenCancelled() throws Exception {
AtomicBoolean ready = new AtomicBoolean(false);
AtomicBoolean cancelled = new AtomicBoolean(false);
when(delegate.isReady()).thenAnswer(i -> ready.get());
when(delegate.isCancelled()).thenAnswer(i -> cancelled.get());
CompletableFuture<Void> onNextCall = CompletableFuture.runAsync(() -> uut.onNext(
new Object()));
Thread.sleep(30);
assertFalse(onNextCall.isDone());
cancelled.set(true);
uut.wakeup();
Thread.sleep(30);
assertTrue(onNextCall.isDone());
verify(delegate, never()).onNext(any());
}
示例2: getAllIncidentsAsync
import java.util.concurrent.CompletableFuture; //導入方法依賴的package包/類
@Override
public CompletableFuture<List<IncidentBean>> getAllIncidentsAsync() {
CompletableFuture<List<IncidentBean>> cf = new CompletableFuture<>();
CompletableFuture.runAsync(() -> {
LOG.info("Performing get {} web service", applicationProperties.getIncidentApiUrl() +"/incidents");
final String restUri = applicationProperties.getIncidentApiUrl() +"/incidents";
ResponseEntity<Resources<IncidentBean>> response = restTemplate.exchange(restUri, HttpMethod.GET, null,
new ParameterizedTypeReference<Resources<IncidentBean>>() {});
// LOG.info("Total Incidents {}", response.getBody().size());
Resources<IncidentBean> beanResources = response.getBody();
Collection<IncidentBean> beanCol = beanResources.getContent();
ArrayList<IncidentBean> beanList= new ArrayList<IncidentBean>(beanCol);
cf.complete( beanList );
LOG.info("Done getting incidents");
});
return cf;
}
示例3: eval
import java.util.concurrent.CompletableFuture; //導入方法依賴的package包/類
public Map<String, Object> eval(String script, IMessage message) {
Map<String, Object> resultMap = new LinkedHashMap<>();
Map<String, Object> scope = new LinkedHashMap<>();
resultMap.put("script", script);
resultMap.put("startedAt", ZonedDateTime.now());
scope.put("bot", message.getClient().getOurUser());
scope.put("client", message.getClient());
scope.put("message", message);
scope.put("content", message.getContent());
scope.put("guild", message.getChannel().isPrivate() ? null : message.getChannel().getGuild());
scope.put("channel", message.getChannel());
scope.put("author", message.getAuthor());
FutureTask<String> evalTask = new FutureTask<>(() -> evalWithScope(script, scope));
try {
CompletableFuture.runAsync(evalTask);
resultMap.put("result", evalTask.get(1, TimeUnit.MINUTES));
} catch (Throwable t) {
log.error("Could not bind result", t);
resultMap.put("throwable", t);
resultMap.put("error", t.getMessage());
evalTask.cancel(true);
}
resultMap.put("stoppedAt", ZonedDateTime.now());
return resultMap;
}
示例4: onEvent
import java.util.concurrent.CompletableFuture; //導入方法依賴的package包/類
@Override
public void onEvent(ConfigEvent event) {
CompletableFuture.runAsync(() -> {
AuditLogEntity entity = new AuditLogEntity();
entity.setName(event.getName());
entity.setTimestamp(event.getTimestamp());
entity.setHost(event.getHost());
entity.setType(event.getType().toString());
entity.setNewSource(event.getNewSource());
entity.setNewOrigin(event.getNewOrigin());
entity.setNewValue(event.getNewValue());
entity.setOldSource(event.getOldSource());
entity.setOldOrigin(event.getOldOrigin());
entity.setOldValue(event.getOldValue());
insertOne(entity);
}, executor);
}
示例5: deployAll
import java.util.concurrent.CompletableFuture; //導入方法依賴的package包/類
/**
* Attempts to concurrently {@link #deploy(ApplicationDescriptor) deploy} each of the application instances that are maintained by this network.
* If one deployment task fails all deployment tasks are cancelled.
*
* @throws Exception if any of the deployments fails
*/
public void deployAll() throws Exception {
final List<CompletableFuture<Void>> deployments = new ArrayList<>();
for (final ApplicationDescriptor application_descriptor : application_descriptors) {
final CompletableFuture<Void> deployment = CompletableFuture.runAsync(() -> {
try {
deploy(application_descriptor);
}
catch (Exception e) {
throw new RuntimeException(e);
}
}, network_executor_service);
deployments.add(deployment);
}
awaitCompletion(deployments);
}
示例6: processRequestsInParallel
import java.util.concurrent.CompletableFuture; //導入方法依賴的package包/類
@Test
public void processRequestsInParallel() {
CompletableFuture.runAsync(() -> coordinator.run(sagaJson));
CompletableFuture.runAsync(() -> coordinator.run(anotherSagaJson));
waitAtMost(2, SECONDS).until(() -> eventStore.size() == 8);
assertThat(eventStore, containsInAnyOrder(
eventWith(NoOpSagaRequest.SAGA_START_REQUEST, SagaStartedEvent.class),
eventWith(request1, TransactionStartedEvent.class),
eventWith(request1, TransactionEndedEvent.class),
eventWith(NoOpSagaRequest.SAGA_END_REQUEST, SagaEndedEvent.class),
eventWith(NoOpSagaRequest.SAGA_START_REQUEST, SagaStartedEvent.class),
eventWith(request2, TransactionStartedEvent.class),
eventWith(request2, TransactionEndedEvent.class),
eventWith(NoOpSagaRequest.SAGA_END_REQUEST, SagaEndedEvent.class)
));
}
示例7: eachThreadGetsDifferentLocalTxId
import java.util.concurrent.CompletableFuture; //導入方法依賴的package包/類
@Test
public void eachThreadGetsDifferentLocalTxId() throws Exception {
CyclicBarrier barrier = new CyclicBarrier(2);
Runnable runnable = exceptionalRunnable(() -> {
String spanId = UUID.randomUUID().toString();
omegaContext.setLocalTxId(spanId);
barrier.await();
assertThat(omegaContext.localTxId(), is(spanId));
});
CompletableFuture<Void> future1 = CompletableFuture.runAsync(runnable);
CompletableFuture<Void> future2 = CompletableFuture.runAsync(runnable);
CompletableFuture.allOf(future1, future2).join();
}
示例8: githubImport
import java.util.concurrent.CompletableFuture; //導入方法依賴的package包/類
@ResponseBody
@RequestMapping("/githubimport/")
public String githubImport() throws Exception {
if (future != null && !future.isDone()) {
return "import already running";
}
future =
CompletableFuture.runAsync(() -> githubImportService.importDefaultGithubData(), executor);
return "Import started";
}
示例9: startsNewChildSpan
import java.util.concurrent.CompletableFuture; //導入方法依賴的package包/類
@Test
public void startsNewChildSpan() throws Exception {
CyclicBarrier cyclicBarrier = new CyclicBarrier(nThreads);
CompletableFuture<?>[] futures = new CompletableFuture[nThreads];
for (int i = 0; i < nThreads; i++) {
futures[i] = CompletableFuture.runAsync(() -> {
Span currentSpan = tracing.tracer().newTrace().start();
waitTillAllAreReady(cyclicBarrier);
try (SpanInScope spanInScope = tracing.tracer().withSpanInScope(currentSpan)) {
assertThat(tracingAdviser.invoke(spanName, path, supplier), is(expected));
} catch (Throwable throwable) {
fail(throwable.getMessage());
} finally {
currentSpan.finish();
}
}, Executors.newFixedThreadPool(nThreads));
}
CompletableFuture.allOf(futures).join();
assertThat(traces.size(), is(nThreads));
for (Queue<zipkin2.Span> queue : traces.values()) {
zipkin2.Span child = queue.poll();
assertThat(child.name(), is(spanName));
zipkin2.Span parent = queue.poll();
assertThat(child.parentId(), is(parent.id()));
assertThat(child.traceId(), is(parent.traceId()));
assertThat(tracedValues(child), contains(this.getClass().getCanonicalName()));
}
}
示例10: completion
import java.util.concurrent.CompletableFuture; //導入方法依賴的package包/類
/**
* Wrap this instance in a {@link CompletableFuture} on the
* {@link ForkJoinPool#commonPool()}
*
* @return a new {@link CompletableFuture}
*/
public default CompletableFuture<?> completion ()
{
return CompletableFuture.runAsync ( () -> {
try
{
await ();
}
catch ( final Exception e )
{
throw new RuntimeException ( e );
}
} );
}
示例11: createInstanceThroughScheduler
import java.util.concurrent.CompletableFuture; //導入方法依賴的package包/類
public static void createInstanceThroughScheduler(HttpExchange t, BigInteger rank, String numeroFatorizar, int identifier)
{
ExecutorService service = Executors.newCachedThreadPool();
InstanceObject instanceCreated = AutoScaling.startInstance(ec2);
System.out.println("Instance created with id : " + instanceCreated.getInstance().getInstanceId());
lockListOfActiveInstances.lock();
listOfActiveInstances.add(instanceCreated);
//atualizamos este pedido como um que instancia que acabou de ser criada esta a tratar
Request request = new Request(t, rank, numeroFatorizar);
CompletableFuture.runAsync(()->listOfActiveInstances.get(listOfActiveInstances.indexOf(instanceCreated)).addRequestToRequestProcessingList(request),service);
lockListOfActiveInstances.unlock();
//metodo responsavel por iniciar os health checks e a verificacao de CPU da nova instancia criada
//e tambem de reinicializar a verificacao de CPU da instancia que ultrapassou o threshold de utilizacao de CPU
CompletableFuture.runAsync(()->AutoScaling.setupChecksNewInstance(instanceCreated),service);
//antes de enviarmos o pedido para a instancia temos que dar tempo para a instancia comecar
try {
Thread.sleep(AutoScaling.GRACE_PERIOD);
if(identifier == 1) //serve para identificar quem chamou este metodo e consoante aplicamos condicoes diferenteswa
{
lockCreateInstances.lock();
instanceBeingCreated = false; //instancias ja podem ser criadas
lockCreateInstances.unlock();
}
} catch (InterruptedException e) {}
CompletableFuture.runAsync(()->sendToInstance(instanceCreated, numeroFatorizar, t),service);
}
示例12: notifyCompletion
import java.util.concurrent.CompletableFuture; //導入方法依賴的package包/類
@Override
public CompletableFuture<Void> notifyCompletion(final UUID job_id, final Serializable result) {
return CompletableFuture.runAsync(() -> {
if (id_future_map.containsKey(job_id)) {
id_future_map.get(job_id).complete(result);
}
else {
LOGGER.info("Launcher was notified about an unknown job completion " + job_id);
}
});
}
示例13: init
import java.util.concurrent.CompletableFuture; //導入方法依賴的package包/類
@Override
public void init() {
bluetoothManager.addAdapterDiscoveryListener(delegateRegistrar);
initTask = CompletableFuture.runAsync(() -> {
bluetoothManager.getDiscoveredAdapters().forEach(this::registerDelegate);
});
}
示例14: readStreamAsync
import java.util.concurrent.CompletableFuture; //導入方法依賴的package包/類
private void readStreamAsync(Subject<Object> replaySubject, InputStream stream) {
CompletableFuture.runAsync(() -> {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(stream))) {
String line;
while ((line = reader.readLine()) != null) {
replaySubject.onNext(line);
}
replaySubject.onComplete();
} catch (IOException ex) {
replaySubject.onError(ex);
}
});
}
示例15: getByIdAsync
import java.util.concurrent.CompletableFuture; //導入方法依賴的package包/類
@Override
public CompletableFuture<IncidentBean> getByIdAsync(String incidentId) {
CompletableFuture<IncidentBean> cf = new CompletableFuture<>();
CompletableFuture.runAsync(() -> {
LOG.info("Getting incident by ID {}", incidentId);
final String restUri = applicationProperties.getIncidentApiUrl() +"/incidents";
IncidentBean result = restTemplate.getForObject(restUri, IncidentBean.class);
cf.complete(result);
LOG.info("Done getting incident by ID");
});
return cf;
}