当前位置: 首页>>代码示例>>Java>>正文


Java CompletableFuture.runAsync方法代码示例

本文整理汇总了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());
}
 
开发者ID:uweschaefer,项目名称:factcast,代码行数:24,代码来源:BlockingStreamObserver0Test.java

示例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;
}
 
开发者ID:Azure,项目名称:CityPower-Build-Sample,代码行数:18,代码来源:IncidentServiceImpl.java

示例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;
}
 
开发者ID:quanticc,项目名称:sentry,代码行数:26,代码来源:ScriptService.java

示例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);
}
 
开发者ID:scalecube,项目名称:config,代码行数:18,代码来源:MongoConfigEventListener.java

示例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);
}
 
开发者ID:stacs-srg,项目名称:shabdiz,代码行数:25,代码来源:ApplicationNetwork.java

示例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)
  ));
}
 
开发者ID:apache,项目名称:incubator-servicecomb-saga,代码行数:19,代码来源:SagaExecutionComponentTestBase.java

示例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();
}
 
开发者ID:apache,项目名称:incubator-servicecomb-saga,代码行数:18,代码来源:OmegaContextTest.java

示例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";
}
 
开发者ID:couchbaselabs,项目名称:GitTalent,代码行数:11,代码来源:IndexController.java

示例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()));
  }
}
 
开发者ID:apache,项目名称:incubator-servicecomb-java-chassis,代码行数:36,代码来源:ZipkinTracingAdviserTest.java

示例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 );
        }
    } );
}
 
开发者ID:eclipse,项目名称:neoscada,代码行数:20,代码来源:Stopping.java

示例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);

}
 
开发者ID:carlosfaria94,项目名称:CloudPrime,代码行数:32,代码来源:LoadBalancer.java

示例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);
        }
    });
}
 
开发者ID:stacs-srg,项目名称:shabdiz,代码行数:13,代码来源:WorkerNetwork.java

示例13: init

import java.util.concurrent.CompletableFuture; //导入方法依赖的package包/类
@Override
public void init() {
    bluetoothManager.addAdapterDiscoveryListener(delegateRegistrar);
    initTask = CompletableFuture.runAsync(() -> {
        bluetoothManager.getDiscoveredAdapters().forEach(this::registerDelegate);
    });
}
 
开发者ID:sputnikdev,项目名称:bluetooth-manager,代码行数:8,代码来源:CombinedDeviceGovernorImpl.java

示例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);
        }
    });
}
 
开发者ID:ccremer,项目名称:clustercode,代码行数:14,代码来源:ExternalProcessServiceImpl.java

示例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;
}
 
开发者ID:Azure,项目名称:CityPower-Build-Sample,代码行数:14,代码来源:IncidentServiceImpl.java


注:本文中的java.util.concurrent.CompletableFuture.runAsync方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。