Java Code Examples for java.util.concurrent.Future
The following examples show how to use
java.util.concurrent.Future.
These examples are extracted from open source projects.
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 Project: openjdk-jdk9 Author: AdoptOpenJDK File: CompileTheWorld.java License: GNU General Public License v2.0 | 7 votes |
@SuppressWarnings("try") private void compileMethod(HotSpotResolvedJavaMethod method) throws InterruptedException, ExecutionException { if (methodFilters != null && !MethodFilter.matches(methodFilters, method)) { return; } if (excludeMethodFilters != null && MethodFilter.matches(excludeMethodFilters, method)) { return; } Future<?> task = threadPool.submit(new Runnable() { @Override public void run() { waitToRun(); try (OverrideScope s = config.apply()) { compileMethod(method, classFileCounter); } } }); if (threadPool.getCorePoolSize() == 1) { task.get(); } }
Example #2
Source Project: MFL Author: HebiRobotics File: Mat5Writer.java License: Apache License 2.0 | 6 votes |
/** * Makes sure that all written arrays were written to the sink, and that * the (optional) subsystem offset has been set. May be called more than * once. * * @return this * @throws IOException if writing to the Sink fails */ public Mat5Writer flush() throws IOException { // Write all entries for (Future<FlushAction> action : flushActions) { try { action.get().run(); } catch (Exception e) { throw new IOException(e); } } // Lastly, update subsystem offset in the (non-reduced) header if (headerStart >= 0 && subsysLocation > 0) { Mat5File.updateSubsysOffset(headerStart, subsysLocation, sink); subsysLocation = 0; } return this; }
Example #3
Source Project: netbeans Author: apache File: CommandHttpLifeCycleTest.java License: Apache License 2.0 | 6 votes |
/** * Test GlasFissh create-cluster administration HTTP command execution. */ @Test(groups = {"http-commands"}, dependsOnMethods = {"testCreateCluster"}) public void testCreateClusterInstance() { PayaraServer server = payaraServer(); Command command = new CommandCreateInstance(INSTANCE_NAME, CLUSTER_NAME, "localhost-" + server.getDomainName()); ResultString result = null; String value = null; try { Future<ResultString> future = ServerAdmin.<ResultString>exec(server, command); try { result = future.get(); value = result.getValue(); } catch (InterruptedException | ExecutionException ie) { fail("FetchLogData command execution failed: " + ie.getMessage()); } } catch (PayaraIdeException gfie) { fail("FetchLogData command execution failed: " + gfie.getMessage()); } if (result == null || result.getState() != TaskState.COMPLETED) { fail(value); } assertNotNull(value); }
Example #4
Source Project: grpc-nebula-java Author: grpc-nebula File: CascadingTest.java License: Apache License 2.0 | 6 votes |
/** * Test that cancellation via call cancellation propagates down the call. */ @Test public void testCascadingCancellationViaRpcCancel() throws Exception { observedCancellations = new CountDownLatch(2); receivedCancellations = new CountDownLatch(3); Future<?> chainReady = startChainingServer(3); Future<SimpleResponse> future = futureStub.unaryCall(SimpleRequest.getDefaultInstance()); chainReady.get(5, TimeUnit.SECONDS); future.cancel(true); assertTrue(future.isCancelled()); if (!observedCancellations.await(5, TimeUnit.SECONDS)) { fail("Expected number of cancellations not observed by clients"); } if (!receivedCancellations.await(5, TimeUnit.SECONDS)) { fail("Expected number of cancellations to be received by servers not observed"); } }
Example #5
Source Project: graphicsfuzz Author: google File: FuzzerServerIntegrationTests.java License: Apache License 2.0 | 6 votes |
@Test public void willErrorOnAMismatchedJobId() throws Exception { final String worker = newWorkerName(); assertNotNull(worker); final Job job = new Job().setImageJob(new ImageJob()).setJobId(1); final Future<Job> submitting = this.submitJob(worker, job, 1); try { final Job otherJob = new Job().setImageJob(new ImageJob()).setJobId(2); final Job got = this.getAJob(worker); assertEquals(job.getJobId(), got.getJobId()); thrown.expect(TException.class); this.fuzzerService.jobDone(worker, otherJob); } finally { submitting.cancel(true); } }
Example #6
Source Project: jstarcraft-ai Author: HongZhaoHua File: MatrixTestCase.java License: Apache License 2.0 | 6 votes |
@Test public void testSize() throws Exception { EnvironmentContext context = EnvironmentFactory.getContext(); Future<?> task = context.doTask(() -> { int dimension = 10; MathMatrix dataMatrix = getRandomMatrix(dimension); Assert.assertThat(dataMatrix.getKnownSize() + dataMatrix.getUnknownSize(), CoreMatchers.equalTo(dataMatrix.getRowSize() * dataMatrix.getColumnSize())); int elementSize = 0; float sumValue = 0F; for (MatrixScalar term : dataMatrix) { elementSize++; sumValue += term.getValue(); } Assert.assertThat(elementSize, CoreMatchers.equalTo(dataMatrix.getElementSize())); Assert.assertThat(sumValue, CoreMatchers.equalTo(dataMatrix.getSum(false))); }); task.get(); }
Example #7
Source Project: microprofile-fault-tolerance Author: eclipse File: DisableAnnotationGloballyEnableOnMethodTest.java License: Apache License 2.0 | 6 votes |
/** * Test whether Bulkhead is enabled on {@code waitWithBulkhead()} * * @throws InterruptedException interrupted * @throws ExecutionException task was aborted * */ @Test public void testBulkhead() throws ExecutionException, InterruptedException { ExecutorService executor = Executors.newFixedThreadPool(10); // Start two executions at once CompletableFuture<Void> waitingFuture = new CompletableFuture<>(); Future<?> result1 = executor.submit(() -> disableClient.waitWithBulkhead(waitingFuture)); Future<?> result2 = executor.submit(() -> disableClient.waitWithBulkhead(waitingFuture)); try { disableClient.waitForBulkheadExecutions(2); // Try to start a third execution. This would throw a BulkheadException if Bulkhead is enabled. // Bulkhead is enabled on the method, so expect exception Assert.assertThrows(BulkheadException.class, () -> disableClient.waitWithBulkhead(CompletableFuture.completedFuture(null))); } finally { // Clean up executor and first two executions executor.shutdown(); waitingFuture.complete(null); result1.get(); result2.get(); } }
Example #8
Source Project: systemds Author: tugraz-isds File: FrameReaderBinaryBlockParallel.java License: Apache License 2.0 | 6 votes |
@Override protected void readBinaryBlockFrameFromHDFS( Path path, JobConf job, FileSystem fs, FrameBlock dest, long rlen, long clen ) throws IOException, DMLRuntimeException { int numThreads = OptimizerUtils.getParallelBinaryReadParallelism(); try { //create read tasks for all files ExecutorService pool = CommonThreadPool.get(numThreads); ArrayList<ReadFileTask> tasks = new ArrayList<>(); for( Path lpath : IOUtilFunctions.getSequenceFilePaths(fs, path) ) tasks.add(new ReadFileTask(lpath, job, fs, dest)); //wait until all tasks have been executed List<Future<Object>> rt = pool.invokeAll(tasks); pool.shutdown(); //check for exceptions for( Future<Object> task : rt ) task.get(); } catch (Exception e) { throw new IOException("Failed parallel read of binary block input.", e); } }
Example #9
Source Project: microprofile-fault-tolerance Author: eclipse File: AsyncClassLevelTimeoutClient.java License: Apache License 2.0 | 6 votes |
/** * serviceA is a slow running service that will take 5 seconds in normal operation. Here it is * configured to time out after 2 seconds. * @return the result as a Future * @throws InterruptedException the interrupted exception */ public Future<Connection> serviceA() throws InterruptedException { Connection conn = new Connection() { { Thread.sleep(TCKConfig.getConfig().getTimeoutInMillis(5000)); } @Override public String getData() { return "serviceA DATA"; } }; return CompletableFuture.completedFuture(conn); }
Example #10
Source Project: smallrye-fault-tolerance Author: smallrye File: FutureFallbackTest.java License: Apache License 2.0 | 5 votes |
@Test public void shouldSucceed() throws Exception { TestInvocation<Future<String>> invocation = TestInvocation.immediatelyReturning(() -> completedFuture("invocation")); TestThread<Future<String>> result = runOnTestThread(new Fallback<>(invocation, "test invocation", this::fallback, SetOfThrowables.ALL, SetOfThrowables.EMPTY, null)); Future<String> future = result.await(); assertThat(future.get()).isEqualTo("invocation"); }
Example #11
Source Project: relight Author: ittianyu File: State.java License: Apache License 2.0 | 5 votes |
public void dispose() { disposed = true; for (Future future : updateStateMap.values()) { if (future.isDone()) continue; future.cancel(false); } updateStateMap = null; }
Example #12
Source Project: hermes Author: ctripcorp File: BaseConsumerTask.java License: Apache License 2.0 | 5 votes |
private PullMessageResultCommandV5 waitForBrokerResult(Future<PullMessageResultCommandV5> resultFuture, long timeout) throws InterruptedException, ExecutionException { PullMessageResultCommandV5 result = null; try { result = resultFuture.get(timeout, TimeUnit.MILLISECONDS); } catch (TimeoutException e) { // do nothing } return result; }
Example #13
Source Project: smallrye-fault-tolerance Author: smallrye File: CommandInterceptorTest.java License: Apache License 2.0 | 5 votes |
@Test public void testHelloAsyncTimeoutFallback() throws InterruptedException, ExecutionException { Object result = service.sayHelloAsyncTimeoutFallback(); assertTrue(result instanceof Future); @SuppressWarnings("unchecked") Future<String> future = (Future<String>) result; assertEquals(MyFallbackHandler.FALLBACK, future.get()); }
Example #14
Source Project: servicecomb-pack Author: apache File: PendingTaskRunner.java License: Apache License 2.0 | 5 votes |
public Future<?> run() { return Executors.newSingleThreadScheduledExecutor() .scheduleWithFixedDelay(() -> { try { pendingTasks.take().run(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }, 0, delay, MILLISECONDS); }
Example #15
Source Project: microprofile-fault-tolerance Author: eclipse File: CircuitBreakerRetryTest.java License: Apache License 2.0 | 5 votes |
/** * Analogous to testCircuitOpenWithMoreRetriesAsync but execution failures are caused by timeouts. */ @Test public void testCircuitOpenWithMultiTimeoutsAsync() { int invokeCounter = 0; Future<Connection> result = clientForCBWithRetryAsync.serviceC(); try { result.get(TCKConfig.getConfig().getTimeoutInMillis(10000), TimeUnit.MILLISECONDS); // Expected to finish after < 1 second // serviceC should retry until the CB threshold is reached. At that point a CircuitBreakerOpenException // should be thrown. Assert if this does not happen. invokeCounter = clientForCBWithRetryAsync.getCounterForInvokingServiceC(); Assert.fail("serviceC should retry in testCircuitOpenWithMultiTimeouts on iteration " + invokeCounter); } catch (ExecutionException executionException) { // Expected execution exception wrapping CircuitBreakerOpenException MatcherAssert.assertThat("Thrown exception is the wrong type", executionException.getCause(), instanceOf(CircuitBreakerOpenException.class)); // Expected on iteration 4 invokeCounter = clientForCBWithRetryAsync.getCounterForInvokingServiceC(); if (invokeCounter < 4) { Assert.fail("serviceC should retry in testCircuitOpenWithMultiTimeouts on iteration " + invokeCounter); } } catch (Exception ex) { // Not Expected invokeCounter = clientForCBWithRetryAsync.getCounterForInvokingServiceC(); Assert.fail("serviceC should retry or throw a CircuitBreakerOpenException in testCircuitOpenWithMultiTimeouts on iteration " + invokeCounter + ", caught exception: " + ex); } invokeCounter = clientForCBWithRetryAsync.getCounterForInvokingServiceC(); Assert.assertEquals(invokeCounter, 4, "The number of executions should be 4"); }
Example #16
Source Project: remote-monitoring-services-java Author: Azure File: KeyVault.java License: MIT License | 5 votes |
/** * Private helper method that gets the access token for the authorization and resource depending on which variables are supplied in the environment. * * @param authorization * @param resource * @return * @throws ExecutionException * @throws InterruptedException * @throws MalformedURLException * @throws Exception */ private AuthenticationResult getAccessToken(String authorization, String resource) throws InterruptedException, ExecutionException, MalformedURLException { AuthenticationResult result = null; //Starts a service to fetch access token. ExecutorService service = null; try { service = Executors.newFixedThreadPool(1); AuthenticationContext context = new AuthenticationContext(authorization, false, service); Future<AuthenticationResult> future = null; //Acquires token based on client ID and client secret. if (!StringUtils.isEmpty(this.clientSecret) && !StringUtils.isEmpty(this.clientId)) { ClientCredential credentials = new ClientCredential(this.clientId, this.clientSecret); future = context.acquireToken(resource, credentials, null); } result = future.get(); } finally { service.shutdown(); } if (result == null) { log.error("Failed to get authentication token for key vault."); throw new RuntimeException("Authentication results were null."); } return result; }
Example #17
Source Project: reactive-streams-in-java Author: adamldavis File: ReactorDemo.java License: Apache License 2.0 | 5 votes |
@Override public Future<String> doParallelStringConcatAsync(int count) { BiConsumer<StringBuilder, Object> collector = (stringBuilder, o) -> stringBuilder.append(o); return Flux.range(0, count) .map(i -> "i=" + i) .window(10) .flatMap(flux -> flux.subscribeOn(Schedulers.parallel()) .collect(() -> new StringBuilder(), collector)) .collect(() -> new StringBuilder(), collector) .map(StringBuilder::toString) .single().toFuture(); }
Example #18
Source Project: SpringBoot2.0 Author: drinkagain File: FutureService.java License: Apache License 2.0 | 5 votes |
@Async public Future<String> futureTest() throws InterruptedException { System.out.println("任务执行开始,需要:" + 1000 + "ms"); for (int i = 0; i < 10; i++) { Thread.sleep(100); System.out.println("do:" + i); } System.out.println("完成任务"); return new AsyncResult<>(Thread.currentThread().getName()); }
Example #19
Source Project: com.zsmartsystems.zigbee Author: zsmartsystems File: ZigBeeApi.java License: Eclipse Public License 1.0 | 5 votes |
/** * Views group membership from device. * * @param device the device * @param groupId the group ID * @return the command result future */ public Future<CommandResult> viewMembership(final ZigBeeEndpoint device, final int groupId) { final ViewGroupCommand command = new ViewGroupCommand(); command.setGroupId(groupId); command.setDestinationAddress(device.getEndpointAddress()); return networkManager.sendTransaction(command, new ZclTransactionMatcher()); }
Example #20
Source Project: relight Author: ittianyu File: FutureSet.java License: Apache License 2.0 | 5 votes |
@Override public boolean isDone() { for (Future future : futures) { if (!future.isDone()) { return false; } } return true; }
Example #21
Source Project: qpid-broker-j Author: apache File: ReplicatedEnvironmentFacadeTest.java License: Apache License 2.0 | 5 votes |
@Test public void testReplicaTransactionBeginsImmediately() throws Exception { ReplicatedEnvironmentFacade master = createMaster(); String nodeName2 = TEST_NODE_NAME + "_2"; String host = "localhost"; int port = _portHelper.getNextAvailable(); String node2NodeHostPort = host + ":" + port; final ReplicatedEnvironmentFacade replica = createReplica(nodeName2, node2NodeHostPort, new NoopReplicationGroupListener() ); // close the master master.close(); // try to create a transaction in a separate thread // and make sure that transaction is created immediately. ExecutorService service = Executors.newSingleThreadExecutor(); try { Future<Transaction> future = service.submit(new Callable<Transaction>(){ @Override public Transaction call() throws Exception { return replica.beginTransaction(null); } }); Transaction transaction = future.get(_timeout, TimeUnit.SECONDS); assertNotNull("Transaction was not created during expected time", transaction); transaction.abort(); } finally { service.shutdown(); } }
Example #22
Source Project: ms-identity-java-webapp Author: Azure-Samples File: AuthHelper.java License: MIT License | 5 votes |
private IAuthenticationResult getAuthResultByAuthCode( HttpServletRequest httpServletRequest, AuthorizationCode authorizationCode, String currentUri) throws Throwable { IAuthenticationResult result; ConfidentialClientApplication app; try { app = createClientApplication(); String authCode = authorizationCode.getValue(); AuthorizationCodeParameters parameters = AuthorizationCodeParameters.builder( authCode, new URI(currentUri)). build(); Future<IAuthenticationResult> future = app.acquireToken(parameters); result = future.get(); } catch (ExecutionException e) { throw e.getCause(); } if (result == null) { throw new ServiceUnavailableException("authentication result was null"); } SessionManagementHelper.storeTokenCacheInSession(httpServletRequest, app.tokenCache().serialize()); return result; }
Example #23
Source Project: microprofile-fault-tolerance Author: eclipse File: Bulkhead10MethodAsynchronousBean.java License: Apache License 2.0 | 5 votes |
@Override @Bulkhead(10) @Asynchronous public Future test(BackendTestDelegate action) throws InterruptedException { Utils.log("in business method of bean " + this.getClass().getName() ); return action.perform(); }
Example #24
Source Project: datawave Author: NationalSecurityAgency File: QueryWebsocket.java License: Apache License 2.0 | 5 votes |
@OnMessage public void handleMessage(final Session session, QueryMessage message) { switch (message.getType()) { case CREATE: { if (session.getUserProperties().get(ACTIVE_QUERY_FUTURE) != null) { session.getAsyncRemote().sendObject( new QueryResponseMessage(ResponseType.CREATION_FAILURE, "Query already active. Only one query per websocket is allowed.")); } else { CreateQueryMessage cqm = (CreateQueryMessage) message; String logicName = (String) session.getUserProperties().get(LOGIC_NAME); QueryObserver observer = new QueryObserver(log, session); Long startTime = System.nanoTime(); Long loginTime = null; try { loginTime = Long.valueOf((String) session.getUserProperties().get(REQUEST_LOGIN_TIME_HEADER)); } catch (Exception e) { // Ignore -- login time won't be available } Future<?> activeQuery = queryExecutorBean.executeAsync(logicName, cqm.getParameters(), startTime, loginTime, observer); session.getUserProperties().put(ACTIVE_QUERY_FUTURE, activeQuery); } } break; case CANCEL: { cancelActiveQuery(session); } break; } }
Example #25
Source Project: SpringAll Author: wuyouzhuguli File: TestController.java License: MIT License | 5 votes |
@GetMapping("testRequestMerge") public void testRequerstMerge() throws InterruptedException, ExecutionException { Future<User> f1 = userService.findUser(1L); Future<User> f2 = userService.findUser(2L); Future<User> f3 = userService.findUser(3L); f1.get(); f2.get(); f3.get(); Thread.sleep(200); Future<User> f4 = userService.findUser(4L); f4.get(); }
Example #26
Source Project: java-master Author: jufeng98 File: Shop.java License: Apache License 2.0 | 5 votes |
public Future<Double> getPriceAsync1(String product) { return CompletableFuture.supplyAsync(() -> { try { TimeUnit.MILLISECONDS.sleep(500 + RandomUtils.nextInt(10, 1000)); } catch (InterruptedException ignored) { } // 模拟价格 return RandomUtils.nextDouble(1, 10) * product.charAt(0) + product.charAt(1); }); }
Example #27
Source Project: stream-registry Author: ExpediaGroup File: ConsumerEventHandlerForKafka.java License: Apache License 2.0 | 5 votes |
private Future<SendResult<SpecificRecord, SpecificRecord>> sendConsumerNotificationEvent(NotificationEvent<Consumer> event) { return sendEntityNotificationEvent( consumerToKeyRecord, consumerToValueRecord, kafkaTemplate::send, notificationEventsTopic, event ); }
Example #28
Source Project: openjdk-jdk9 Author: AdoptOpenJDK File: ThreadPoolExecutorSubclassTest.java License: GNU General Public License v2.0 | 5 votes |
/** * completed submit of runnable returns successfully */ public void testSubmitRunnable() throws Exception { final ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10)); try (PoolCleaner cleaner = cleaner(e)) { Future<?> future = e.submit(new NoOpRunnable()); future.get(); assertTrue(future.isDone()); } }
Example #29
Source Project: smallrye-fault-tolerance Author: smallrye File: AsyncTimeout.java License: Apache License 2.0 | 5 votes |
@Override public Future<V> apply(InvocationContext<Future<V>> ctx) throws Exception { AsyncTimeoutTask<Future<V>> task = new AsyncTimeoutTask<>("AsyncTimeout", () -> delegate.apply(ctx)); ctx.registerEventHandler(TimeoutEvent.class, task::timedOut); executor.execute(task); try { return task.get(); } catch (ExecutionException e) { throw sneakyThrow(e.getCause()); } }
Example #30
Source Project: jstarcraft-ai Author: HongZhaoHua File: SymmetryMatrixTestCase.java License: Apache License 2.0 | 5 votes |
@Test public void testProduct() throws Exception { EnvironmentContext context = EnvironmentFactory.getContext(); Future<?> task = context.doTask(() -> { int dimension = 10; MathMatrix randomMatrix = getRandomMatrix(dimension); MathMatrix dataMatrix = getZeroMatrix(dimension); MathMatrix markMatrix = DenseMatrix.valueOf(dimension, dimension); MathVector dataVector = dataMatrix.getRowVector(0); MathVector markVector = markMatrix.getRowVector(0); markMatrix.dotProduct(randomMatrix, true, randomMatrix, false, MathCalculator.SERIAL); dataMatrix.dotProduct(randomMatrix, true, randomMatrix, false, MathCalculator.SERIAL); Assert.assertTrue(equalMatrix(dataMatrix, markMatrix)); dataMatrix.dotProduct(randomMatrix, true, randomMatrix, false, MathCalculator.PARALLEL); Assert.assertTrue(equalMatrix(dataMatrix, markMatrix)); MathVector leftVector = randomMatrix.getRowVector(RandomUtility.randomInteger(dimension)); MathVector rightVector = randomMatrix.getRowVector(RandomUtility.randomInteger(dimension)); markVector.dotProduct(randomMatrix, false, rightVector, MathCalculator.SERIAL); dataVector.dotProduct(randomMatrix, false, rightVector, MathCalculator.SERIAL); Assert.assertTrue(equalVector(dataVector, markVector)); dataVector.dotProduct(randomMatrix, false, rightVector, MathCalculator.PARALLEL); Assert.assertTrue(equalVector(dataVector, markVector)); markVector.dotProduct(leftVector, randomMatrix, false, MathCalculator.SERIAL); dataVector.dotProduct(leftVector, randomMatrix, false, MathCalculator.SERIAL); Assert.assertTrue(equalVector(dataVector, markVector)); dataVector.dotProduct(leftVector, randomMatrix, false, MathCalculator.PARALLEL); Assert.assertTrue(equalVector(dataVector, markVector)); }); task.get(); }