/** @return waits if necessary for the computation to complete and then returns the result * @throws GdxRuntimeException if there was an error */ public T get () { try { return future.get(); } catch (InterruptedException ex) { return null; } catch (ExecutionException ex) { throw new GdxRuntimeException(ex.getCause()); } } }
@Override public void runWithTimeout(Runnable runnable, long timeoutDuration, TimeUnit timeoutUnit) throws TimeoutException, InterruptedException { checkNotNull(runnable); checkNotNull(timeoutUnit); checkPositiveTimeout(timeoutDuration); Future<?> future = executor.submit(runnable); try { future.get(timeoutDuration, timeoutUnit); } catch (InterruptedException | TimeoutException e) { future.cancel(true /* mayInterruptIfRunning */); throw e; } catch (ExecutionException e) { wrapAndThrowRuntimeExecutionExceptionOrError(e.getCause()); throw new AssertionError(); } }
public static void main(final String... args) { final ExecutorService es = Executors.newFixedThreadPool(20); final String ip = "127.0.0.1"; final int timeout = 200; final List<Future<Boolean>> futures = new ArrayList<>(); for (int port = 1; port <= 65535; port++) { futures.add(portIsOpen(es, ip, port, timeout)); } es.shutdown(); int openPorts = 0; for (final Future<Boolean> f : futures) { if (f.get()) { openPorts++; } } System.out.println("There are " + openPorts + " open ports on host " + ip + " (probed with a timeout of " + timeout + "ms)"); }
@Test public void nonSharedEngine() throws Exception { int iterations = 20; this.view.setEngineName("nashorn"); this.view.setRenderFunction("render"); this.view.setSharedEngine(false); this.view.setApplicationContext(this.context); ExecutorService executor = Executors.newFixedThreadPool(4); List<Future<Boolean>> results = new ArrayList<>(); for (int i = 0; i < iterations; i++) { results.add(executor.submit(() -> view.getEngine() != null)); } assertEquals(iterations, results.size()); for (int i = 0; i < iterations; i++) { assertTrue(results.get(i).get()); } executor.shutdown(); }
@Test public void testParallelCompilationWithMultipleQuotasAndClientSessionConcurrency() throws Exception { conf.setBoolVar(HIVE_SERVER2_PARALLEL_COMPILATION, true); conf.setIntVar(HIVE_SERVER2_PARALLEL_COMPILATION_LIMIT, 2); initDriver(conf, 10); List<CommandProcessorResponse> responseList = new ArrayList<>(); List<Callable<List<CommandProcessorResponse>>> callables = new ArrayList<>(); for (int i = 0; i < 5; i++) { callables.add(() -> compileAndRespond(true, 2)); } ExecutorService pool = Executors.newFixedThreadPool(callables.size()); try { List<Future<List<CommandProcessorResponse>>> futures = pool.invokeAll(callables); for (Future<List<CommandProcessorResponse>> future : futures) { responseList.addAll(future.get()); } } finally { pool.shutdown(); } verifyThatWaitingCompileOpsCountIsEqualTo(0); verifyThatTimedOutCompileOpsCountIsZero(responseList); verifyThatConcurrentCompilationWasIndeed(responseList); }
public List<FutureType> submitTasksAndWait(List<? extends Callable<FutureType>> tasks) { List<Future<FutureType>> takes = Lists.newArrayList(tasks.size()); for (Callable<FutureType> callable : tasks) { takes.add(m_completionService.submit(callable)); } List<FutureType> result = Lists.newArrayList(takes.size()); for (Future<FutureType> take : takes) { try { result.add(take.get()); } catch (InterruptedException | ExecutionException e) { throw new TestNGException(e); } } m_executor.shutdown(); return result; } }
private void llapCachePurge(final SessionState ss, final LlapRegistryService llapRegistryService) throws Exception { ExecutorService executorService = Executors.newCachedThreadPool(); List<Future<Long>> futures = new ArrayList<>(); Collection<LlapServiceInstance> instances = llapRegistryService.getInstances().getAll(); for (LlapServiceInstance instance : instances) { futures.add(executorService.submit(new PurgeCallable(ss.getConf(), instance))); } int i = 0; for (LlapServiceInstance instance : instances) { Future<Long> future = futures.get(i); ss.out.println(Joiner.on("\t").join(instance.getHost(), future.get())); i++; } }
@Test public void testMultipleSubscribes() throws InterruptedException, ExecutionException { final TestAsyncErrorObservable o = new TestAsyncErrorObservable("one", "two", null, "three"); Flowable<Notification<String>> m = Flowable.unsafeCreate(o).materialize(); assertEquals(3, m.toList().toFuture().get().size()); assertEquals(3, m.toList().toFuture().get().size()); }
@Test public void testToFutureList() throws InterruptedException, ExecutionException { Observable<String> obs = Observable.just("one", "two", "three"); Future<List<String>> f = obs.toList().toFuture(); assertEquals("one", f.get().get(0)); assertEquals("two", f.get().get(1)); assertEquals("three", f.get().get(2)); }
@Test(/* timeout = 5000, */expected = IndexOutOfBoundsException.class) public void testExceptionWithMoreThanOneElement() throws Throwable { Observable<String> obs = Observable.just("one", "two"); Future<String> f = obs.toFuture(); try { // we expect an exception since there are more than 1 element f.get(); fail("Should have thrown!"); } catch (ExecutionException e) { throw e.getCause(); } }
@Test public void notFoundGet() throws Exception { try { Future<?> future = template.execute(baseUrl + "/status/notfound", HttpMethod.GET, null, null); future.get(); fail("HttpClientErrorException expected"); } catch (ExecutionException ex) { assertTrue(ex.getCause() instanceof HttpClientErrorException); HttpClientErrorException cause = (HttpClientErrorException)ex.getCause(); assertEquals(HttpStatus.NOT_FOUND, cause.getStatusCode()); assertNotNull(cause.getStatusText()); assertNotNull(cause.getResponseBodyAsString()); } }
private void testConcurrency(final CollectionHolder<List<Integer>> holder) throws InterruptedException, ExecutionException { final List<Integer> list = holder.collection; // make a big array that takes a long time to toString() list.addAll(LIST); // Create a thread pool with two threads to cause the most contention on the underlying resource. final ExecutorService threadPool = Executors.newFixedThreadPool(2); // Consumes toStrings final Callable<Integer> consumer = new Callable<Integer>() { @Override public Integer call() { for (int i = 0; i < REPEAT; i++) { // Calls ToStringStyle new ToStringBuilder(holder).append(holder.collection); } return Integer.valueOf(REPEAT); } }; final Collection<Callable<Integer>> tasks = new ArrayList<>(); tasks.add(consumer); tasks.add(consumer); final List<Future<Integer>> futures = threadPool.invokeAll(tasks); for (final Future<Integer> future : futures) { future.get(); } threadPool.shutdown(); threadPool.awaitTermination(1, TimeUnit.SECONDS); } }
@Test public void testGoodBlocking() throws Exception { try (DRPC server = new DRPC(new StormMetricsRegistry(), null, 100)) { Future<String> found = exec.submit(() -> server.executeBlocking("testing", "test")); DRPCRequest request = getNextAvailableRequest(server, "testing"); assertNotNull(request); assertEquals("test", request.get_func_args()); assertNotNull(request.get_request_id()); server.returnResult(request.get_request_id(), "tested"); String result = found.get(10, TimeUnit.MILLISECONDS); assertEquals("tested", result); } }
@Test public void testLoadSegment() throws ExecutionException, InterruptedException, SegmentLoadingException { final List<Future<Boolean>> futures = segments.stream() .map( segment -> executor.submit( () -> segmentManager.loadSegment(segment) ) ) .collect(Collectors.toList()); for (Future<Boolean> eachFuture : futures) { Assert.assertTrue(eachFuture.get()); } assertResult(segments); }
private <T> T callWithTimeout( Callable<T> callable, long timeoutDuration, TimeUnit timeoutUnit, boolean amInterruptible) throws Exception { checkNotNull(callable); checkNotNull(timeoutUnit); checkPositiveTimeout(timeoutDuration); Future<T> future = executor.submit(callable); try { if (amInterruptible) { try { return future.get(timeoutDuration, timeoutUnit); } catch (InterruptedException e) { future.cancel(true); throw e; } } else { return Uninterruptibles.getUninterruptibly(future, timeoutDuration, timeoutUnit); } } catch (ExecutionException e) { throw throwCause(e, true /* combineStackTraces */); } catch (TimeoutException e) { future.cancel(true); throw new UncheckedTimeoutException(e); } }
public void run() { ExecutorService service = Executors.newSingleThreadExecutor(); Callable<Object> callable = new Callable<Object>() { public Object call() throws Exception { runTestMethod(); return null; } }; Future<Object> result = service.submit(callable); service.shutdown(); try { boolean terminated = service.awaitTermination(timeout, TimeUnit.MILLISECONDS); if (!terminated) { service.shutdownNow(); } result.get(0, TimeUnit.MILLISECONDS); // throws the exception if one occurred during the invocation } catch (TimeoutException e) { addFailure(new Exception(String.format("test timed out after %d milliseconds", timeout))); } catch (Exception e) { addFailure(e); } } });
@Test(expected = CancellationException.class) public void testGetWithTimeoutAfterCancel() throws Exception { Flowable<String> obs = Flowable.never(); Future<String> f = obs.toFuture(); boolean cancelled = f.cancel(true); assertTrue(cancelled); // because OperationNeverComplete never does f.get(Long.MAX_VALUE, TimeUnit.NANOSECONDS); // Future.get() docs require this to throw }
ExecutorService exec = Executors.newFixedThreadPool(50); final Future f = exec.submit(task1); exec.submit(new Runnable() { @Override public void run() { f.get(); // do stuff } });
private void assertFutureWithException(Future<Object> result, TestableAsyncUncaughtExceptionHandler exceptionHandler) { try { result.get(); } catch (InterruptedException ex) { fail("Should not have failed with InterruptedException: " + ex); } catch (ExecutionException ex) { // expected assertEquals("Wrong exception cause", UnsupportedOperationException.class, ex.getCause().getClass()); } assertFalse("handler should never be called with Future return type", exceptionHandler.isCalled()); }