List of usage examples for java.util.concurrent CompletableFuture supplyAsync
public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier, Executor executor)
From source file:async.nio2.Main.java
public static void main(String[] args) throws IOException, InterruptedException, ExecutionException { if (args.length == 3) { PORT = Integer.valueOf(args[0]); NO_CLIENTS = Integer.valueOf(args[1]); NO_SAMPLES = Integer.valueOf(args[2]); }// w w w . j ava 2s . com if (PORT < 0) { System.err.println("Error: port < 0"); System.exit(1); } if (NO_CLIENTS < 1) { System.err.println("Error: #clients < 1"); System.exit(1); } if (NO_SAMPLES < 1) { System.err.println("Error: #samples < 1"); System.exit(1); } AsynchronousChannelGroup groupServer = AsynchronousChannelGroup .withThreadPool(Executors.newFixedThreadPool(1)); AsynchronousChannelGroup groupClient = AsynchronousChannelGroup .withThreadPool(Executors.newFixedThreadPool(1)); Server server = Server.newInstance(new InetSocketAddress("localhost", PORT), groupServer); InetSocketAddress localAddress = server.getLocalAddress(); String hostname = localAddress.getHostName(); int port = localAddress.getPort(); ExecutorService es = Executors.newFixedThreadPool(2); System.out.printf("%03d clients on %s:%d, %03d runs each. All times in s.%n", NO_CLIENTS, hostname, port, NO_SAMPLES); range(0, NO_CLIENTS).unordered().parallel() .mapToObj(i -> CompletableFuture.supplyAsync(newClient(localAddress, groupClient), es).join()) .map(array -> Arrays.stream(array).reduce(new DescriptiveStatistics(), Main::accumulate, Main::combine)) .map(Main::toEvaluationString).forEach(System.out::println); es.shutdown(); es.awaitTermination(5, TimeUnit.SECONDS); groupClient.shutdown(); groupClient.awaitTermination(5, TimeUnit.SECONDS); server.close(); groupServer.shutdown(); groupServer.awaitTermination(5, TimeUnit.SECONDS); }
From source file:com.nike.cerberus.endpoints.authentication.AuthenticateUser.java
@Override public CompletableFuture<ResponseInfo<AuthResponse>> execute(final RequestInfo<Void> request, final Executor longRunningTaskExecutor, final ChannelHandlerContext ctx) { return CompletableFuture.supplyAsync(() -> { final UserCredentials credentials = extractCredentials( request.getHeaders().get(HttpHeaders.AUTHORIZATION)); return ResponseInfo.newBuilder(authenticationService.authenticate(credentials)).build(); }, longRunningTaskExecutor);//www . j a va2 s . co m }
From source file:de.ks.file.FileStore.java
public CompletableFuture<FileReference> getReference(File file) { if (!file.exists()) { throw new IllegalArgumentException("File " + file + " does not exist"); }/* ww w .ja v a 2 s . c o m*/ CompletableFuture<String> md5Sum = CompletableFuture.supplyAsync(() -> getMd5(file), executorService); return md5Sum.thenApply(md5 -> resolveReference(md5, file)); }
From source file:com.nike.cerberus.endpoints.admin.GetSDBMetaData.java
@SuppressWarnings("ConstantConditions") // it lies @Override/*from w w w . java2s . co m*/ public CompletableFuture<ResponseInfo<SDBMetaDataResult>> doExecute(final RequestInfo<Void> request, final Executor longRunningTaskExecutor, final ChannelHandlerContext ctx, final SecurityContext securityContext) { return CompletableFuture.supplyAsync(() -> ResponseInfo .newBuilder(metaDataService.getSDBMetaData(getLimit(request), getOffset(request))).build(), longRunningTaskExecutor); }
From source file:com.redhat.coolstore.api_gateway.ApiGatewayController.java
/** * This /api REST endpoint uses Java 8 concurrency to call two backend services to construct the result * * @return the list//w w w .j a va 2 s. c o m */ @CrossOrigin(maxAge = 3600) @RequestMapping(method = RequestMethod.GET, value = "/products", produces = MediaType.APPLICATION_JSON_VALUE) @ApiOperation("Get a list of products") @ResponseBody public List<Product> list() throws ExecutionException, InterruptedException { final CompletableFuture<List<Product>> productList = CompletableFuture .supplyAsync(() -> feignClientFactory.getPricingClient().getService().getProducts(), es); return productList.thenCompose((List<Product> products) -> { List<CompletableFuture<Product>> all = products.stream() .map(p -> productList.thenCombine(_getInventory(p.itemId), (pl, a) -> { p.availability = a; return p; })).collect(Collectors.toList()); return CompletableFuture.allOf(all.toArray(new CompletableFuture[all.size()])) .thenApply(v -> all.stream().map(CompletableFuture::join).collect(Collectors.toList())); }).get(); }
From source file:edu.berkeley.ground.postgres.controllers.GraphController.java
public final CompletionStage<Result> getGraph(String sourceKey) { return CompletableFuture.supplyAsync(() -> { try {/* w w w .jav a 2 s. com*/ return this.cache.getOrElse("graphs", () -> Json.toJson(this.postgresGraphDao.retrieveFromDatabase(sourceKey)), Integer.parseInt(System.getProperty("ground.cache.expire.secs"))); } catch (Exception e) { throw new CompletionException(e); } }, PostgresUtils.getDbSourceHttpContext(this.actorSystem)).thenApply(Results::ok) .exceptionally(e -> GroundUtils.handleException(e, request())); }
From source file:edu.berkeley.ground.postgres.controllers.StructureController.java
public final CompletionStage<Result> getStructure(String sourceKey) { return CompletableFuture.supplyAsync(() -> { try {/*from ww w .j av a2s . c o m*/ return this.cache.getOrElse("structures", () -> Json.toJson(this.postgresStructureDao.retrieveFromDatabase(sourceKey)), Integer.parseInt(System.getProperty("ground.cache.expire.secs"))); } catch (Exception e) { throw new CompletionException(e); } }, PostgresUtils.getDbSourceHttpContext(this.actorSystem)).thenApply(Results::ok) .exceptionally(e -> GroundUtils.handleException(e, request())); }
From source file:edu.berkeley.ground.postgres.controllers.GraphController.java
public final CompletionStage<Result> getGraphVersion(Long id) { return CompletableFuture.supplyAsync(() -> { try {/* w ww . j a v a 2s. c om*/ return this.cache.getOrElse("graph_versions", () -> Json.toJson(this.postgresGraphVersionDao.retrieveFromDatabase(id)), Integer.parseInt(System.getProperty("ground.cache.expire.secs"))); } catch (Exception e) { throw new CompletionException(e); } }, PostgresUtils.getDbSourceHttpContext(this.actorSystem)).thenApply(Results::ok) .exceptionally(e -> GroundUtils.handleException(e, request())); }
From source file:edu.berkeley.ground.postgres.controllers.StructureController.java
public final CompletionStage<Result> getStructureVersion(Long id) { return CompletableFuture.supplyAsync(() -> { try {//w w w .j a v a 2s. c om return this.cache.getOrElse("structure_versions", () -> Json.toJson(this.postgresStructureVersionDao.retrieveFromDatabase(id)), Integer.parseInt(System.getProperty("ground.cache.expire.secs"))); } catch (Exception e) { throw new CompletionException(e); } }, PostgresUtils.getDbSourceHttpContext(this.actorSystem)).thenApply(Results::ok) .exceptionally(e -> GroundUtils.handleException(e, request())); }
From source file:org.trustedanalytics.platformoperations.service.PlatformOperationsScheduler.java
private Runnable platformSummary() { return () -> { if (flag.compareAndSet(false, true)) { try { LOGGER.info("Trigger Platform Summary"); final CompletableFuture<ComponentSummary> componentSummary = CompletableFuture .supplyAsync(new ComponentDiscoverTask(nats), executor) .thenApply(messages -> new ComponentMetricsTask("DEA", messages).get()) .thenApply(ComponentSummary::new); final CompletableFuture<ControllerSummary> controllerSummary = CompletableFuture .supplyAsync(new ControllerMetricsTask(client), executor); CompletableFuture.allOf(componentSummary, controllerSummary).get(10, TimeUnit.MINUTES); repository.save(new PlatformSummary(componentSummary.get(1, TimeUnit.MINUTES), controllerSummary.get(1, TimeUnit.MINUTES))); } catch (TimeoutException | ExecutionException | InterruptedException ex) { LOGGER.error("Exception during fetching metrics: {}" + ex); } finally { flag.set(false);/*from w w w. j a va 2s . com*/ } } else { LOGGER.info("Request skipped, task already submitted!"); } }; }