Java Code Examples for java.util.concurrent.CompletableFuture#supplyAsync()
The following examples show how to use
java.util.concurrent.CompletableFuture#supplyAsync() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: GuavateTest.java From Strata with Apache License 2.0 | 6 votes |
@Test public void test_toCombinedFuture_Void() { CompletableFuture<Void> future1 = new CompletableFuture<>(); future1.complete(null); CountDownLatch latch = new CountDownLatch(1); CompletableFuture<Void> future2 = CompletableFuture.supplyAsync(() -> { try { latch.await(); } catch (InterruptedException ex) { // ignore } return null; }); List<CompletableFuture<Void>> input = ImmutableList.of(future1, future2); CompletableFuture<List<Void>> test = input.stream().collect(Guavate.toCombinedFuture()); assertThat(test.isDone()).isEqualTo(false); latch.countDown(); List<Void> combined = test.join(); assertThat(test.isDone()).isEqualTo(true); assertThat(combined.size()).isEqualTo(2); assertThat(combined.get(0)).isNull(); assertThat(combined.get(1)).isNull(); }
Example 2
Source File: JavaHotCodeReplaceProvider.java From java-debug with Eclipse Public License 1.0 | 6 votes |
@Override public CompletableFuture<List<String>> redefineClasses() { JobHelpers.waitForBuildJobs(10 * 1000); return CompletableFuture.supplyAsync(() -> { List<String> classNames = new ArrayList<>(); List<IResource> resources = new ArrayList<>(); String errorMessage = null; synchronized (this) { classNames.addAll(deltaClassNames); resources.addAll(deltaResources); deltaResources.clear(); deltaClassNames.clear(); errorMessage = doHotCodeReplace(resources, classNames); } if (!classNames.isEmpty() && errorMessage != null) { throw AdapterUtils.createCompletionException(errorMessage, ErrorCode.HCR_FAILURE); } return classNames; }); }
Example 3
Source File: CompletableFutureDemo.java From xyTalk-pc with GNU Affero General Public License v3.0 | 6 votes |
private String demoNoBlock() { CompletableFuture<String> resultCompletableFuture = CompletableFuture.supplyAsync(new Supplier<String>() { public String get() { try { TimeUnit.SECONDS.sleep(6); //int i = 1/0; 如果有异常,则永远也不返回,即永远得不到结果 System.out.println("执行线程:"+Thread.currentThread().getName()); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } return "hello"; } }, executor); resultCompletableFuture.thenAcceptAsync(new Consumer<String>() { @Override public void accept(String t) { System.out.println(t); System.out.println("回调线程:"+Thread.currentThread().getName()); frame.setTitle(t); } }, executor); System.out.println("直接不阻塞返回了######"); return "直接不阻塞返回了######"; }
Example 4
Source File: AbstractCachedDataManager.java From LuckPerms with MIT License | 6 votes |
@Override public @NonNull CompletableFuture<? extends C> reload(@NonNull QueryOptions queryOptions) { Objects.requireNonNull(queryOptions, "queryOptions"); // get the previous value - we can reuse the same instance C previous = this.cache.getIfPresent(queryOptions); // invalidate the previous value until we're done recalculating this.cache.invalidate(queryOptions); clearRecent(); // request recalculation from the cache if (previous != null) { return CompletableFuture.supplyAsync( () -> this.cache.get(queryOptions, c -> this.cacheLoader.reload(c, previous)), CaffeineFactory.executor() ); } else { return CompletableFuture.supplyAsync( () -> this.cache.get(queryOptions), CaffeineFactory.executor() ); } }
Example 5
Source File: Database.java From MySQL with MIT License | 5 votes |
/** * Executes an SQL update asynchronously * * @param update Update to be run * @return result code, see {@link java.sql.PreparedStatement#executeUpdate()} * internally throws SQLException If the query cannot be executed * internally throws ClassNotFoundException If the driver cannot be found; see {@link #getConnection()} */ public CompletableFuture<Integer> updateAsync(String update) { return CompletableFuture.supplyAsync(() -> { int results = 0; try { results = update(update); } catch (SQLException e) { e.printStackTrace(); } return results; }); }
Example 6
Source File: ConcurrentAccessExperiment.java From tutorials with MIT License | 5 votes |
public final Map<String,String> doWork(Map<String,String> map, int threads, int slots) { CompletableFuture<?>[] requests = new CompletableFuture<?>[threads * slots]; for (int i = 0; i < threads; i++) { requests[slots * i + 0] = CompletableFuture.supplyAsync(putSupplier(map, i)); requests[slots * i + 1] = CompletableFuture.supplyAsync(getSupplier(map, i)); requests[slots * i + 2] = CompletableFuture.supplyAsync(getSupplier(map, i)); requests[slots * i + 3] = CompletableFuture.supplyAsync(getSupplier(map, i)); } CompletableFuture.allOf(requests).join(); return map; }
Example 7
Source File: BindParameterTypesTest.java From pgadba with BSD 2-Clause "Simplified" License | 5 votes |
@Test public void bindFutureNullAsInteger4() throws ExecutionException, InterruptedException, TimeoutException { CompletableFuture<Integer> f = CompletableFuture.supplyAsync(() -> null); try (Session session = ds.getSession()) { CompletionStage<Integer> idF = session.<Integer>rowOperation("select $1::int4 as t") .set("$1", f, PgAdbaType.INTEGER) .collect(singleCollector(Integer.class)) .submit() .getCompletionStage(); assertNull(get10(idF.toCompletableFuture())); } }
Example 8
Source File: ConcurrencyIT.java From grakn with GNU Affero General Public License v3.0 | 5 votes |
private <T extends Element> void insertElements(Session session, List<T> elements, int threads, int insertsPerCommit) throws ExecutionException, InterruptedException { ExecutorService executorService = Executors.newFixedThreadPool(threads); int listSize = elements.size(); int listChunk = listSize / threads + 1; List<CompletableFuture<Void>> asyncInsertions = new ArrayList<>(); for (int threadNo = 0; threadNo < threads; threadNo++) { boolean lastChunk = threadNo == threads - 1; final int startIndex = threadNo * listChunk; int endIndex = (threadNo + 1) * listChunk; if (endIndex > listSize && lastChunk) endIndex = listSize; List<T> subList = elements.subList(startIndex, endIndex); System.out.println("indices: " + startIndex + "-" + endIndex + " , size: " + subList.size()); CompletableFuture<Void> asyncInsert = CompletableFuture.supplyAsync(() -> { long start2 = System.currentTimeMillis(); Transaction tx = session.transaction(Transaction.Type.WRITE); int inserted = 0; for (int elementId = 0; elementId < subList.size(); elementId++) { T element = subList.get(elementId); GraqlInsert insert = Graql.insert(element.patternise(Graql.var("x" + elementId).var()).statements()); tx.execute(insert); if (inserted % insertsPerCommit == 0) { tx.commit(); inserted = 0; tx = session.transaction(Transaction.Type.WRITE); } inserted++; } tx.commit(); System.out.println("Thread: " + Thread.currentThread().getId() + " elements: " + subList.size() + " time: " + (System.currentTimeMillis() - start2)); return null; }, executorService); asyncInsertions.add(asyncInsert); } CompletableFuture.allOf(asyncInsertions.toArray(new CompletableFuture[]{})).get(); executorService.shutdown(); }
Example 9
Source File: KinesisShardDetectorTest.java From amazon-kinesis-client with Apache License 2.0 | 5 votes |
@Test public void testListShardsResouceInUse() { final CompletableFuture<ListShardsResponse> future = CompletableFuture.supplyAsync(() -> { throw ResourceInUseException.builder().build(); }); when(client.listShards(any(ListShardsRequest.class))).thenReturn(future); final List<Shard> shards = shardDetector.listShards(); assertThat(shards, nullValue()); verify(client).listShards(any(ListShardsRequest.class)); }
Example 10
Source File: CompletionStageShoppingCardService.java From Hands-On-Reactive-Programming-in-Spring-5 with MIT License | 5 votes |
@Override public CompletionStage<Output> calculate(Input value) { return CompletableFuture.supplyAsync(() -> { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } return new Output(); }); }
Example 11
Source File: Bmv2DeviceHandshaker.java From onos with Apache License 2.0 | 4 votes |
private CompletableFuture<Boolean> disconnectFromBmv2Pre() { return CompletableFuture.supplyAsync(() -> { removePreClient(); return true; }); }
Example 12
Source File: JwtTokenExtractor.java From botbuilder-java with MIT License | 4 votes |
@SuppressWarnings("unchecked") private CompletableFuture<ClaimsIdentity> validateToken( String token, String channelId, List<String> requiredEndorsements ) { return CompletableFuture.supplyAsync(() -> { DecodedJWT decodedJWT = JWT.decode(token); OpenIdMetadataKey key = this.openIdMetadata.getKey(decodedJWT.getKeyId()); if (key == null) { return null; } Verification verification = JWT.require(Algorithm.RSA256(key.key, null)) .acceptLeeway(tokenValidationParameters.clockSkew.getSeconds()); try { verification.build().verify(token); // If specified, validate the signing certificate. if ( tokenValidationParameters.validateIssuerSigningKey && key.certificateChain != null && key.certificateChain.size() > 0 ) { // Note that decodeCertificate will return null if the cert could not // be decoded. This would likely be the case if it were in an unexpected // encoding. Going to err on the side of ignoring this check. // May want to reconsider this and throw on null cert. X509Certificate cert = decodeCertificate(key.certificateChain.get(0)); if (cert != null && !isCertValid(cert)) { throw new JWTVerificationException("Signing certificate is not valid"); } } // Note: On the Emulator Code Path, the endorsements collection is null so the // validation code below won't run. This is normal. if (key.endorsements != null) { // Validate Channel / Token Endorsements. For this, the channelID present on the // Activity needs to be matched by an endorsement. boolean isEndorsed = EndorsementsValidator.validate(channelId, key.endorsements); if (!isEndorsed) { throw new AuthenticationException( String.format( "Could not validate endorsement for key: %s with endorsements: %s", key.key.toString(), StringUtils.join(key.endorsements) ) ); } // Verify that additional endorsements are satisfied. If no additional // endorsements are expected, the requirement is satisfied as well boolean additionalEndorsementsSatisfied = requiredEndorsements.stream() .allMatch( (endorsement) -> EndorsementsValidator .validate(endorsement, key.endorsements) ); if (!additionalEndorsementsSatisfied) { throw new AuthenticationException( String.format( "Could not validate additional endorsement for key: %s with endorsements: %s", key.key.toString(), StringUtils.join(requiredEndorsements) ) ); } } if (!this.allowedSigningAlgorithms.contains(decodedJWT.getAlgorithm())) { throw new AuthenticationException( String.format( "Could not validate algorithm for key: %s with algorithms: %s", decodedJWT.getAlgorithm(), StringUtils.join(allowedSigningAlgorithms) ) ); } return new ClaimsIdentity(decodedJWT); } catch (JWTVerificationException ex) { LOGGER.warn(ex.getMessage()); throw new AuthenticationException(ex); } }, ExecutorFactory.getExecutor()); }
Example 13
Source File: AbstractStatefulPersistentActorSpec.java From ts-reaktive with MIT License | 4 votes |
@Override public CompletionStage<Results<MyEvent>> handle(MyState state, String cmd) { return CompletableFuture.supplyAsync(() -> { throw new RuntimeException("Simulated failure"); }); }
Example 14
Source File: BlobServerPutTest.java From Flink-CEPplus with Apache License 2.0 | 4 votes |
/** * [FLINK-6020] * Tests that concurrent put operations will only upload the file once to the {@link BlobStore} * and that the files are not corrupt at any time. * * @param jobId * job ID to use (or <tt>null</tt> if job-unrelated) * @param blobType * whether the BLOB should become permanent or transient */ private void testConcurrentPutOperations( @Nullable final JobID jobId, final BlobKey.BlobType blobType) throws IOException, InterruptedException, ExecutionException { final Configuration config = new Configuration(); config.setString(BlobServerOptions.STORAGE_DIRECTORY, temporaryFolder.newFolder().getAbsolutePath()); BlobStore blobStore = mock(BlobStore.class); int concurrentPutOperations = 2; int dataSize = 1024; final CountDownLatch countDownLatch = new CountDownLatch(concurrentPutOperations); final byte[] data = new byte[dataSize]; ArrayList<CompletableFuture<BlobKey>> allFutures = new ArrayList<>(concurrentPutOperations); ExecutorService executor = Executors.newFixedThreadPool(concurrentPutOperations); try (final BlobServer server = new BlobServer(config, blobStore)) { server.start(); for (int i = 0; i < concurrentPutOperations; i++) { CompletableFuture<BlobKey> putFuture = CompletableFuture .supplyAsync( () -> { try { BlockingInputStream inputStream = new BlockingInputStream(countDownLatch, data); BlobKey uploadedKey = put(server, jobId, inputStream, blobType); // check the uploaded file's contents (concurrently) verifyContents(server, jobId, uploadedKey, data); return uploadedKey; } catch (IOException e) { throw new CompletionException(new FlinkException( "Could not upload blob.", e)); } }, executor); allFutures.add(putFuture); } FutureUtils.ConjunctFuture<Collection<BlobKey>> conjunctFuture = FutureUtils.combineAll(allFutures); // wait until all operations have completed and check that no exception was thrown Collection<BlobKey> blobKeys = conjunctFuture.get(); Iterator<BlobKey> blobKeyIterator = blobKeys.iterator(); assertTrue(blobKeyIterator.hasNext()); BlobKey blobKey = blobKeyIterator.next(); // make sure that all blob keys are the same while (blobKeyIterator.hasNext()) { verifyKeyDifferentHashEquals(blobKey, blobKeyIterator.next()); } // check the uploaded file's contents verifyContents(server, jobId, blobKey, data); // check that we only uploaded the file once to the blob store if (blobType == PERMANENT_BLOB) { verify(blobStore, times(1)).put(any(File.class), eq(jobId), eq(blobKey)); } else { // can't really verify much in the other cases other than that the put operations should // work and not corrupt files verify(blobStore, times(0)).put(any(File.class), eq(jobId), eq(blobKey)); } } finally { executor.shutdownNow(); } }
Example 15
Source File: RestClientTest.java From Flink-CEPplus with Apache License 2.0 | 4 votes |
/** * Tests that we fail the operation if the remote connection closes. */ @Test public void testConnectionClosedHandling() throws Exception { final Configuration config = new Configuration(); config.setLong(RestOptions.IDLENESS_TIMEOUT, 5000L); try (final ServerSocket serverSocket = new ServerSocket(0); final RestClient restClient = new RestClient(RestClientConfiguration.fromConfiguration(config), TestingUtils.defaultExecutor())) { final String targetAddress = "localhost"; final int targetPort = serverSocket.getLocalPort(); // start server final CompletableFuture<Socket> socketCompletableFuture = CompletableFuture.supplyAsync(CheckedSupplier.unchecked(serverSocket::accept)); final CompletableFuture<EmptyResponseBody> responseFuture = restClient.sendRequest( targetAddress, targetPort, new TestMessageHeaders(), EmptyMessageParameters.getInstance(), EmptyRequestBody.getInstance(), Collections.emptyList()); Socket connectionSocket = null; try { connectionSocket = socketCompletableFuture.get(TIMEOUT, TimeUnit.SECONDS); } catch (TimeoutException ignored) { // could not establish a server connection --> see that the response failed socketCompletableFuture.cancel(true); } if (connectionSocket != null) { // close connection connectionSocket.close(); } try { responseFuture.get(); } catch (ExecutionException ee) { if (!ExceptionUtils.findThrowable(ee, IOException.class).isPresent()) { throw ee; } } } }
Example 16
Source File: AckChainTest.java From smallrye-reactive-messaging with Apache License 2.0 | 4 votes |
@Incoming("A") @Outgoing("B") public CompletionStage<Integer> process(int p) { return CompletableFuture.supplyAsync(() -> p + 1); }
Example 17
Source File: TestContainerStateManagerIntegration.java From hadoop-ozone with Apache License 2.0 | 4 votes |
@Test @Ignore("TODO:HDDS-1159") public void testGetMatchingContainerMultipleThreads() throws IOException, InterruptedException { ContainerWithPipeline container1 = scm.getClientProtocolServer(). allocateContainer(SCMTestUtils.getReplicationType(conf), SCMTestUtils.getReplicationFactor(conf), OzoneConsts.OZONE); Map<Long, Long> container2MatchedCount = new ConcurrentHashMap<>(); // allocate blocks using multiple threads int numBlockAllocates = 100000; for (int i = 0; i < numBlockAllocates; i++) { CompletableFuture.supplyAsync(() -> { ContainerInfo info = containerManager .getMatchingContainer(OzoneConsts.GB * 3, OzoneConsts.OZONE, container1.getPipeline()); container2MatchedCount .compute(info.getContainerID(), (k, v) -> v == null ? 1L : v + 1); return null; }); } // make sure pipeline has has numContainerPerOwnerInPipeline number of // containers. Assert.assertEquals(scm.getPipelineManager() .getNumberOfContainers(container1.getPipeline().getId()), numContainerPerOwnerInPipeline); Thread.sleep(5000); long threshold = 2000; // check the way the block allocations are distributed in the different // containers. for (Long matchedCount : container2MatchedCount.values()) { // TODO: #CLUTIL Look at the division of block allocations in different // containers. LOG.error("Total allocated block = " + matchedCount); Assert.assertTrue(matchedCount <= numBlockAllocates / container2MatchedCount.size() + threshold && matchedCount >= numBlockAllocates / container2MatchedCount.size() - threshold); } }
Example 18
Source File: StandaloneCommandExecutor.java From centraldogma with Apache License 2.0 | 4 votes |
private CompletableFuture<Void> createRepository(CreateRepositoryCommand c) { return CompletableFuture.supplyAsync(() -> { projectManager.get(c.projectName()).repos().create(c.repositoryName(), c.timestamp(), c.author()); return null; }, repositoryWorker); }
Example 19
Source File: KeyToPageIndexTest.java From herddb with Apache License 2.0 | 3 votes |
public static final CompletableFuture<?> submitJob(ExecutorService service, KeyToPageIndex index, Bytes key, Long newPage, Long expectedPage) { final ConcurrentPutIfTask[] tasks = createTasks(index, key, newPage, expectedPage); @SuppressWarnings("unchecked") final CompletableFuture<Long>[] futures = new CompletableFuture[tasks.length]; for (int i = 0; i < tasks.length; ++i) { futures[i] = CompletableFuture.supplyAsync(tasks[i]::call, service); } return CompletableFuture.allOf(futures); }
Example 20
Source File: HttpBuilder.java From http-builder-ng with Apache License 2.0 | 2 votes |
/** * Executes an asynchronous GET request on the configured URI (asynchronous alias to `get(Consumer)`), with additional configuration provided by the * configuration function. * * This method is generally used for Java-specific configuration. * * [source,java] * ---- * HttpBuilder http = HttpBuilder.configure(config -> { * config.getRequest().setUri("http://localhost:10101"); * }); * CompletableFuture<Object> future = http.getAsync(config -> { * config.getRequest().getUri().setPath("/foo"); * }); * Object result = future.get(); * ---- * * The `configuration` function allows additional configuration for this request based on the {@link HttpConfig} interface. * * @param configuration the additional configuration closure (delegated to {@link HttpConfig}) * @return the resulting content wrapped in a {@link CompletableFuture} */ public CompletableFuture<Object> getAsync(final Consumer<HttpConfig> configuration) { return CompletableFuture.supplyAsync(() -> get(configuration), getExecutor()); }