java.util.concurrent.Future Java Examples

The following examples show how to use java.util.concurrent.Future. 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: CompileTheWorld.java    From openjdk-jdk9 with GNU General Public License v2.0 7 votes vote down vote up
@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 File: DisableAnnotationGloballyEnableOnMethodTest.java    From microprofile-fault-tolerance with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #3
Source File: CascadingTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #4
Source File: FuzzerServerIntegrationTests.java    From graphicsfuzz with Apache License 2.0 6 votes vote down vote up
@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 #5
Source File: CommandHttpLifeCycleTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #6
Source File: AsyncClassLevelTimeoutClient.java    From microprofile-fault-tolerance with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #7
Source File: MatrixTestCase.java    From jstarcraft-ai with Apache License 2.0 6 votes vote down vote up
@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 #8
Source File: Mat5Writer.java    From MFL with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #9
Source File: SymmetryMatrixTestCase.java    From jstarcraft-ai with Apache License 2.0 5 votes vote down vote up
@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();
}
 
Example #10
Source File: ProducerPipeline.java    From hermes with Apache License 2.0 5 votes vote down vote up
@Override
public Future<SendResult> put(Object payload) {
	ProducerMessage<?> msg = (ProducerMessage<?>) payload;

	String topic = msg.getTopic();
	PipelineSink<Future<SendResult>> sink = m_sinkManager.getSink(topic);
	PipelineContext<Future<SendResult>> ctx = new DefaultPipelineContext<Future<SendResult>>(m_valveRegistry.getValveList(), sink);

	ctx.next(msg);

	return ctx.getResult();
}
 
Example #11
Source File: FrameReaderBinaryBlockParallel.java    From systemds with Apache License 2.0 5 votes vote down vote up
@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 #12
Source File: CommandInterceptorTest.java    From smallrye-fault-tolerance with Apache License 2.0 5 votes vote down vote up
@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 #13
Source File: PendingTaskRunner.java    From servicecomb-pack with Apache License 2.0 5 votes vote down vote up
public Future<?> run() {
  return Executors.newSingleThreadScheduledExecutor()
      .scheduleWithFixedDelay(() -> {
        try {
          pendingTasks.take().run();
        } catch (InterruptedException e) {
          Thread.currentThread().interrupt();
        }
      }, 0, delay, MILLISECONDS);
}
 
Example #14
Source File: ScheduledExecutorTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * completed submit of callable returns result
 */
public void testSubmitCallable() throws Exception {
    final ExecutorService e = new ScheduledThreadPoolExecutor(2);
    try (PoolCleaner cleaner = cleaner(e)) {
        Future<String> future = e.submit(new StringTask());
        String result = future.get();
        assertSame(TEST_STRING, result);
    }
}
 
Example #15
Source File: BaseConsumerTask.java    From hermes with Apache License 2.0 5 votes vote down vote up
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 #16
Source File: FutureFallbackTest.java    From smallrye-fault-tolerance with Apache License 2.0 5 votes vote down vote up
@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 #17
Source File: OpenProjectsScopeProvider.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public boolean initialize(Lookup context, AtomicBoolean cancel) {
    Future<Project[]> openProjects = OpenProjects.getDefault().openProjects();
    
    Project[] projects;
    try {
        projects = openProjects.get();
    } catch (InterruptedException | ExecutionException ex) {
        return false;
    }
    
    if(projects == null || projects.length == 0) {
        return false;
    }

    Set<FileObject> srcRoots = new HashSet<>();
    
    for (Project project : projects) {
        ProjectInformation pi = ProjectUtils.getInformation(project);
        final SourceGroup[] sourceGroups = ProjectUtils.getSources(pi.getProject()).getSourceGroups(JavaProjectConstants.SOURCES_TYPE_JAVA);
        for (int i = 0; i < sourceGroups.length; i++) {
            srcRoots.add(sourceGroups[i].getRootFolder());
        }
    }
    if(srcRoots.isEmpty()) {
        return false;
    }
    scope = Scope.create(srcRoots, null, null);

    return true;
}
 
Example #18
Source File: TestController.java    From SpringAll with MIT License 5 votes vote down vote up
@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 #19
Source File: ReactorDemo.java    From reactive-streams-in-java with Apache License 2.0 5 votes vote down vote up
@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 #20
Source File: AsyncTimeout.java    From smallrye-fault-tolerance with Apache License 2.0 5 votes vote down vote up
@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 #21
Source File: FutureService.java    From SpringBoot2.0 with Apache License 2.0 5 votes vote down vote up
@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 #22
Source File: ZigBeeApi.java    From com.zsmartsystems.zigbee with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * 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 #23
Source File: ThreadPoolExecutorSubclassTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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 #24
Source File: FutureSet.java    From relight with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isDone() {
    for (Future future : futures) {
        if (!future.isDone()) {
            return false;
        }
    }
    return true;
}
 
Example #25
Source File: ReplicatedEnvironmentFacadeTest.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
@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 #26
Source File: AuthHelper.java    From ms-identity-java-webapp with MIT License 5 votes vote down vote up
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 #27
Source File: ConsumerEventHandlerForKafka.java    From stream-registry with Apache License 2.0 5 votes vote down vote up
private Future<SendResult<SpecificRecord, SpecificRecord>> sendConsumerNotificationEvent(NotificationEvent<Consumer> event) {
  return sendEntityNotificationEvent(
      consumerToKeyRecord,
      consumerToValueRecord,
      kafkaTemplate::send,
      notificationEventsTopic,
      event
  );
}
 
Example #28
Source File: Bulkhead10MethodAsynchronousBean.java    From microprofile-fault-tolerance with Apache License 2.0 5 votes vote down vote up
@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 #29
Source File: QueryWebsocket.java    From datawave with Apache License 2.0 5 votes vote down vote up
@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 #30
Source File: Shop.java    From java-master with Apache License 2.0 5 votes vote down vote up
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);
    });
}