List of usage examples for java.util.concurrent Future isDone
boolean isDone();
From source file:org.betaconceptframework.astroboa.test.engine.AbstractRepositoryTest.java
protected SerializationReport exportObjects(ContentObjectCriteria contentObjectCriteria, SerializationConfiguration serializationConfiguration) throws InterruptedException, ExecutionException { long timeStart = System.currentTimeMillis(); Future<SerializationReport> exportReportFuture = serializationDao .serializeObjectsUsingCriteria(contentObjectCriteria, serializationConfiguration); //Wait until export is finished while (!exportReportFuture.isDone()) { final long timePassed = System.currentTimeMillis() - timeStart; Assert.assertTrue(timePassed < (5 * 60 * 1000), "Export does not seem to have finished. Time passed " + timePassed + " ms"); }//from w w w.ja va 2 s . c o m return exportReportFuture.get(); }
From source file:org.apache.http.impl.nio.conn.TestPoolingHttpClientAsyncConnectionManager.java
@Test public void testReleaseConnectionIncompleteRoute() throws Exception { final HttpHost target = new HttpHost("localhost"); final HttpRoute route = new HttpRoute(target); final Future<NHttpClientConnection> future = connman.requestConnection(route, "some state", 1000L, 2000L, TimeUnit.MILLISECONDS, connCallback); Assert.assertNotNull(future);/*from ww w . j a va2 s .co m*/ Mockito.verify(pool).lease(Matchers.same(route), Matchers.eq("some state"), Matchers.eq(1000L), Matchers.eq(2000L), Matchers.eq(TimeUnit.MILLISECONDS), poolEntryCallbackCaptor.capture()); final FutureCallback<CPoolEntry> callaback = poolEntryCallbackCaptor.getValue(); final Log log = Mockito.mock(Log.class); final CPoolEntry poolentry = new CPoolEntry(log, "some-id", route, conn, -1, TimeUnit.MILLISECONDS); callaback.completed(poolentry); Assert.assertTrue(future.isDone()); final NHttpClientConnection managedConn = future.get(); Mockito.verify(connCallback).completed(Matchers.<NHttpClientConnection>any()); Mockito.when(conn.isOpen()).thenReturn(Boolean.TRUE); connman.releaseConnection(managedConn, "new state", 5, TimeUnit.SECONDS); Mockito.verify(pool).release(poolentry, false); }
From source file:org.apereo.portal.io.xml.JaxbPortalDataHandlerService.java
/** * Used by batch import and export to wait for queued tasks to complete. Handles fail-fast behavior * if any of the tasks threw and exception by canceling all queued futures and logging a summary of * the failures. All completed futures are removed from the queue. * * @param futures Queued futures to check for completeness * @param wait If true it will wait for all futures to complete, if false only check for completed futures * @return a list of futures that either threw exceptions or timed out *///from w w w .jav a 2 s .c o m protected List<FutureHolder<?>> waitForFutures(final Queue<? extends FutureHolder<?>> futures, final PrintWriter reportWriter, final File reportDirectory, final boolean wait) throws InterruptedException { final List<FutureHolder<?>> failedFutures = new LinkedList<FutureHolder<?>>(); for (Iterator<? extends FutureHolder<?>> futuresItr = futures.iterator(); futuresItr.hasNext();) { final FutureHolder<?> futureHolder = futuresItr.next(); //If waiting, or if not waiting but the future is already done do the get final Future<?> future = futureHolder.getFuture(); if (wait || (!wait && future.isDone())) { futuresItr.remove(); try { //Don't bother doing a get() on canceled futures if (!future.isCancelled()) { if (this.maxWait > 0) { future.get(this.maxWait, this.maxWaitTimeUnit); } else { future.get(); } reportWriter.printf(REPORT_FORMAT, "SUCCESS", futureHolder.getDescription(), futureHolder.getExecutionTimeMillis()); } } catch (CancellationException e) { //Ignore cancellation exceptions } catch (ExecutionException e) { logger.error("Failed: " + futureHolder); futureHolder.setError(e); failedFutures.add(futureHolder); reportWriter.printf(REPORT_FORMAT, "FAIL", futureHolder.getDescription(), futureHolder.getExecutionTimeMillis()); try { final String dataReportName = SafeFilenameUtils.makeSafeFilename( futureHolder.getDataType() + "_" + futureHolder.getDataName() + ".txt"); final File dataReportFile = new File(reportDirectory, dataReportName); final PrintWriter dataReportWriter = new PrintWriter( new BufferedWriter(new FileWriter(dataReportFile))); try { dataReportWriter.println( "FAIL: " + futureHolder.getDataType() + " - " + futureHolder.getDataName()); dataReportWriter.println( "--------------------------------------------------------------------------------"); e.getCause().printStackTrace(dataReportWriter); } finally { IOUtils.closeQuietly(dataReportWriter); } } catch (Exception re) { logger.warn("Failed to write error report for failed " + futureHolder + ", logging root failure here", e.getCause()); } } catch (TimeoutException e) { logger.warn("Failed: " + futureHolder); futureHolder.setError(e); failedFutures.add(futureHolder); future.cancel(true); reportWriter.printf(REPORT_FORMAT, "TIMEOUT", futureHolder.getDescription(), futureHolder.getExecutionTimeMillis()); } } } return failedFutures; }
From source file:org.apache.http.impl.nio.conn.TestPoolingHttpClientAsyncConnectionManager.java
@Test public void testRequestReleaseConnection() throws Exception { final HttpHost target = new HttpHost("localhost"); final HttpRoute route = new HttpRoute(target); final Future<NHttpClientConnection> future = connman.requestConnection(route, "some state", 1000L, 2000L, TimeUnit.MILLISECONDS, connCallback); Assert.assertNotNull(future);/* ww w . java 2 s. co m*/ Mockito.verify(pool).lease(Matchers.same(route), Matchers.eq("some state"), Matchers.eq(1000L), Matchers.eq(2000L), Matchers.eq(TimeUnit.MILLISECONDS), poolEntryCallbackCaptor.capture()); final FutureCallback<CPoolEntry> callaback = poolEntryCallbackCaptor.getValue(); final Log log = Mockito.mock(Log.class); final CPoolEntry poolentry = new CPoolEntry(log, "some-id", route, conn, -1, TimeUnit.MILLISECONDS); poolentry.markRouteComplete(); callaback.completed(poolentry); Assert.assertTrue(future.isDone()); final NHttpClientConnection managedConn = future.get(); Mockito.verify(connCallback).completed(Matchers.<NHttpClientConnection>any()); Mockito.when(conn.isOpen()).thenReturn(Boolean.TRUE); connman.releaseConnection(managedConn, "new state", 5, TimeUnit.SECONDS); Mockito.verify(pool).release(poolentry, true); Assert.assertEquals("new state", poolentry.getState()); final Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(poolentry.getUpdated()); cal.add(Calendar.SECOND, 5); Assert.assertEquals(cal.getTimeInMillis(), poolentry.getExpiry()); }
From source file:org.rhq.server.control.command.AbstractInstall.java
protected void waitForRHQServerToInitialize(Future<Integer> installerExitCode) throws Exception { try {//from w w w . ja v a 2 s.com final long messageInterval = 30000L; final long problemMessageInterval = 120000L; long timerStart = System.currentTimeMillis(); long intervalStart = timerStart; while (!isRHQServerInitialized()) { Long now = System.currentTimeMillis(); if (installerExitCode.isDone() && installerExitCode.get().intValue() != RHQControl.EXIT_CODE_OK) { stopServer(); throw new RuntimeException("Installer failed with code " + installerExitCode.get().intValue() + ", shut down server"); } if ((now - intervalStart) > messageInterval) { long totalWait = (now - timerStart); if (totalWait < problemMessageInterval) { log.info("Still waiting for server to start..."); } else { long minutes = totalWait / 60000; log.info("It has been over [" + minutes + "] minutes - you may want to ensure your server startup is proceeding as expected. You can check the log at [" + new File(getBaseDir(), "logs/server.log").getPath() + "]."); timerStart = now; } intervalStart = now; } Thread.sleep(5000); } } catch (IOException e) { log.error("An error occurred while checking to see if the server is initialized: " + e.getMessage()); throw e; } catch (InterruptedException e) { // Don't think we need to log any details here throw e; } }
From source file:org.springframework.amqp.rabbit.admin.RabbitBrokerAdmin.java
@ManagedOperation public void startBrokerApplication() { RabbitStatus status = getStatus();/*from w w w.j av a 2 s .c o m*/ if (status.isReady()) { logger.info("Rabbit Application already running."); return; } if (!status.isAlive()) { logger.info("Rabbit Process not running."); startNode(); return; } logger.info("Starting Rabbit Application."); // This call in particular seems to be prone to hanging, so do it in the background... final CountDownLatch latch = new CountDownLatch(1); Future<Object> result = executor.submit(new Callable<Object>() { public Object call() throws Exception { try { return executeAndConvertRpc("rabbit", "start"); } finally { latch.countDown(); } } }); boolean started = false; try { started = latch.await(timeout, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { Thread.currentThread().interrupt(); result.cancel(true); return; } if (timeout > 0 && started) { if (!waitForReadyState() && !result.isDone()) { result.cancel(true); } } }
From source file:org.springframework.ide.eclipse.boot.dash.test.CloudFoundryClientTest.java
@Test public void testApplicationLogConnection() throws Exception { client = createClient(CfTestTargetParams.fromEnv()); String appName = appHarness.randomAppName(); IApplicationLogConsole listener = mock(IApplicationLogConsole.class); Cancellation token = client.streamLogs(appName, listener); assertNotNull(token);/*from w w w.j av a 2 s .c om*/ Future<Void> pushResult = doAsync(() -> { CFPushArguments params = new CFPushArguments(); params.setAppName(appName); params.setApplicationData(getTestZip("testapp")); params.setBuildpack("staticfile_buildpack"); push(params); }); ACondition.waitFor("push", TimeUnit.MINUTES.toMillis(4), () -> { assertTrue(pushResult.isDone()); }); pushResult.get(); BootDashModelTest.waitForJobsToComplete(); verify(listener, atLeastOnce()).onMessage(any()); }
From source file:org.dasein.cloud.google.compute.server.ServerSupport.java
@Override public @Nonnull Iterable<String> launchMany(final @Nonnull VMLaunchOptions withLaunchOptions, final @Nonnegative int count) throws CloudException, InternalException { if (count < 1) { throw new InternalException( "Invalid attempt to launch less than 1 virtual machine (requested " + count + ")."); }/*from w w w. j a v a 2 s. c om*/ if (count == 1) { return Collections.singleton(launch(withLaunchOptions).getProviderVirtualMachineId()); } final List<Future<String>> results = new ArrayList<Future<String>>(); // windows on GCE follows same naming constraints as regular instances, 1-62 lower and numbers, must begin with a letter. NamingConstraints c = NamingConstraints.getAlphaNumeric(1, 63).withNoSpaces() .withRegularExpression("(?:[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?)").lowerCaseOnly().constrainedBy('-'); String baseHost = c.convertToValidName(withLaunchOptions.getHostName(), Locale.US); if (baseHost == null) { baseHost = withLaunchOptions.getHostName(); } for (int i = 1; i <= count; i++) { String hostName = c.incrementName(baseHost, i); String friendlyName = withLaunchOptions.getFriendlyName() + "-" + i; VMLaunchOptions options = withLaunchOptions .copy(hostName == null ? withLaunchOptions.getHostName() + "-" + i : hostName, friendlyName); results.add(launchAsync(options)); } PopulatorThread<String> populator = new PopulatorThread<String>(new JiteratorPopulator<String>() { @Override public void populate(@Nonnull Jiterator<String> iterator) throws Exception { List<Future<String>> original = results; List<Future<String>> copy = new ArrayList<Future<String>>(); Exception exception = null; boolean loaded = false; while (!original.isEmpty()) { for (Future<String> result : original) { if (result.isDone()) { try { iterator.push(result.get()); loaded = true; } catch (Exception e) { exception = e; } } else { copy.add(result); } } original = copy; // copy has to be a new list else we'll get into concurrently modified list state copy = new ArrayList<Future<String>>(); } if (exception != null && !loaded) { throw exception; } } }); populator.populate(); return populator.getResult(); }
From source file:org.apache.hadoop.fs.nfs.stream.NFSBufferedInputStream.java
private StreamBlock getBlock(long blockId) throws IOException { // Block is current if (currentBlock != null && currentBlock.getBlockId() == blockId) { LOG.debug("Returning 1 blockId=" + blockId); return currentBlock; }//from w ww .j a v a 2 s .c o m // Issue prefetch for upcoming blocks if (doPrefetch) { if (blockId >= prefetchBlockLimit) { prefetchBlockLimit += (long) (Math.min(fileLength, this.splitSize) >> readBlockSizeBits); LOG.info("Changing prefetchBlockLimit to " + prefetchBlockLimit); } for (long bid = blockId + 1; bid < blockId + DEFAULT_READAHEAD_SIZE && bid < prefetchBlockLimit; ++bid) { if (!ongoing.containsKey(bid) && !cache.containsKey(bid)) { StreamBlock block = new StreamBlock(readBlockSizeBits); block.setBlockId(bid); block.setReady(false); cache.put(bid, block); Read task = new Read(store, handle, credentials, statistics, bid, block); Future<Read> future = executors.submit(task); ongoing.put(bid, future); } } } // Block is being fetched, so wait for it if (ongoing.containsKey(blockId)) { Future<Read> future = ongoing.get(blockId); while (true) { try { LOG.debug("Waiting for read task to complete ongoing reading block id=" + blockId); future.get(); break; } catch (InterruptedException interrupted) { continue; } catch (Exception error) { throw new IOException("Read resulted in an error", error); } } } // Some prefetches are done, check for them for (Iterator<Entry<Long, Future<Read>>> iter = ongoing.entrySet().iterator(); iter.hasNext();) { Future<Read> future = iter.next().getValue(); if (future.isDone()) { try { future.get(); iter.remove(); } catch (InterruptedException interrupted) { // Ignore } catch (Exception error) { throw new IOException("Prefetched resulted in error", error); } } } // Keep trying until the block is found while (true) { if (cache.containsKey(blockId)) { StreamBlock block = cache.remove(blockId); assert (block != null); assert (block.getBlockId() == blockId); assert (block.isReady() == true); currentBlock = block; return currentBlock; } if (cache.size() >= 100 * DEFAULT_CACHE_SIZE_IN_BLOCKS) { LOG.error("Cache is wayyy bigger than planned, size=" + cache.size() + " limit=" + DEFAULT_CACHE_SIZE_IN_BLOCKS); } // Issue the read and wait StreamBlock block = new StreamBlock(readBlockSizeBits); block.setBlockId(blockId); block.setReady(false); cache.put(blockId, block); Read task = new Read(store, handle, credentials, statistics, blockId, block); Future<Read> future = executors.submit(task); while (true) { try { future.get(); break; } catch (InterruptedException interrupted) { continue; } catch (Exception error) { throw new IOException("Read resulted in an error", error); } } } }
From source file:de.javakaffee.web.msm.integration.NonStickySessionsIntegrationTest.java
/** * Tests that for uriPattern locking mode requests that don't match the pattern the * session is not locked./*from w ww . j av a2s.c o m*/ */ @Test public void testRequestsDontLockSessionForNotMatchingUriPattern() throws IOException, InterruptedException, HttpException, ExecutionException { final String pathToLock = "/locksession"; setLockingMode(LockingMode.URI_PATTERN, Pattern.compile(pathToLock + ".*")); final String sessionId = get(_httpClient, TC_PORT_1, null).getSessionId(); assertNotNull(sessionId); // perform a request not matching the uri pattern, and in parallel start another request // that should lock the session final long timeToWaitInMillis = 500; final Map<String, String> paramsWait = asMap(PARAM_WAIT, "true", PARAM_MILLIS, String.valueOf(timeToWaitInMillis)); final long start = System.currentTimeMillis(); final Future<Response> response2 = _executor.submit(new Callable<Response>() { @Override public Response call() throws Exception { return get(_httpClient, TC_PORT_1, "/pathNotMatchingLockUriPattern", sessionId, paramsWait); } }); final Future<Response> response3 = _executor.submit(new Callable<Response>() { @Override public Response call() throws Exception { return get(_httpClient, TC_PORT_1, pathToLock, sessionId, paramsWait); } }); response2.get(); response3.get(); assertTrue((System.currentTimeMillis() - start) < (2 * timeToWaitInMillis), "The time for both requests should be less than 2 * the wait time if they don't block each other."); assertEquals(response2.get().getSessionId(), sessionId); assertEquals(response3.get().getSessionId(), sessionId); // now perform a locking request and a not locking in parallel which should also not be blocked final Future<Response> response4 = _executor.submit(new Callable<Response>() { @Override public Response call() throws Exception { return get(_httpClient, TC_PORT_1, pathToLock, sessionId, paramsWait); } }); Thread.sleep(50); final Response response5 = get(_httpClient, TC_PORT_1, "/pathNotMatchingLockUriPattern", sessionId); assertEquals(response5.getSessionId(), sessionId); assertFalse(response4.isDone(), "The non locking request should return before the long, session locking one"); assertEquals(response4.get().getSessionId(), sessionId); }