List of usage examples for java.util.concurrent Future isDone
boolean isDone();
From source file:com.glaf.core.cache.CacheFactory.java
public static String getString(final String key) { boolean waitFor = true; Callable<String> task = new Callable<String>() { @Override/*from w ww.j ava 2 s. co m*/ public String call() throws Exception { try { Cache cache = getCache(); if (cache != null) { String cacheKey = Environment.getCurrentSystemName() + "_" + CACHE_PREFIX + key; if (SystemProperties.getDeploymentSystemName() != null) { cacheKey = SystemProperties.getDeploymentSystemName() + "_" + Environment.getCurrentSystemName() + "_" + CACHE_PREFIX + key; } cacheKey = DigestUtils.md5Hex(cacheKey.getBytes()); Object value = cache.get(cacheKey); if (value != null) { logger.debug("get object'" + key + "' from cache."); return value.toString(); } } } catch (Exception ex) { if (logger.isDebugEnabled()) { ex.printStackTrace(); logger.debug(ex); } } return null; } }; try { Future<String> result = pool.submit(task); long start = System.currentTimeMillis(); // ? if (waitFor) { while (true) { if (System.currentTimeMillis() - start > 2000) { break; } if (result.isDone()) { return result.get(); } } } } catch (Exception e) { logger.error(e); } return null; }
From source file:org.openbase.bco.manager.util.launch.BCOSystemValidator.java
public static boolean check(final Remote<?> remote, final long delayTime) { boolean printed = false; Future<Long> futurePing = remote.ping(); try {/* ww w . ja v a 2s. c o m*/ printed |= print(remote, StringProcessor.fillWithSpaces("Ping", LABEL_RANGE, Alignment.RIGHT) + " " + check(futurePing, delayTime, () -> { if (futurePing.isDone() && !futurePing.isCancelled()) { BCOSystemValidator.computeGlobalPing(futurePing.get()); return " (" + futurePing.get() + ")"; } else { return ""; } })); } catch (CancellationException ex) { throw ex; } catch (Exception ex) { ExceptionPrinter.printHistory(new FatalImplementationErrorException(BCOSystemValidator.class, ex), LOGGER); } boolean online = futurePing.isDone() && !futurePing.isCancelled(); if (online) { // ping does not cause the connection state to be connected, this is done by a data update, therefore wait a bit for the connection state try { remote.waitForConnectionState(ConnectionState.CONNECTED, delayTime); } catch (org.openbase.jul.exception.TimeoutException ex) { // just continue and print error for next step } catch (CouldNotPerformException ex) { ExceptionPrinter.printHistory(ex, LOGGER); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } final ConnectionState connectionState = remote.getConnectionState(); String connectionDescription = StringProcessor.fillWithSpaces("Connection", LABEL_RANGE, Alignment.RIGHT) + " "; switch (connectionState) { case CONNECTED: connectionDescription += AnsiColor.colorize( StringProcessor.fillWithSpaces(OK, STATE_RANGE, Alignment.LEFT), AnsiColor.ANSI_GREEN); break; case DISCONNECTED: case CONNECTING: countError(); connectionDescription += AnsiColor.colorize( StringProcessor.fillWithSpaces(connectionState.name(), STATE_RANGE, Alignment.LEFT), AnsiColor.ANSI_RED); break; case RECONNECTING: connectionDescription += AnsiColor.colorize( StringProcessor.fillWithSpaces(connectionState.name(), STATE_RANGE, Alignment.LEFT), AnsiColor.ANSI_YELLOW); break; default: connectionDescription += AnsiColor.colorize( StringProcessor.fillWithSpaces("UNKNOWN", STATE_RANGE, Alignment.LEFT), AnsiColor.ANSI_RED); countError(); break; } printed |= print(remote, connectionDescription); } if (online) { printed |= print(remote, StringProcessor.fillWithSpaces("Data Cache", LABEL_RANGE, Alignment.RIGHT) + " " + check(remote.getDataFuture(), delayTime)); } else { printed |= print(remote, StringProcessor.fillWithSpaces("Data Cache", LABEL_RANGE, Alignment.RIGHT) + " " + (remote.isDataAvailable() ? AnsiColor.colorize( StringProcessor.fillWithSpaces("OFFLINE", STATE_RANGE, Alignment.LEFT), AnsiColor.ANSI_YELLOW) : AnsiColor.colorize( StringProcessor.fillWithSpaces("EMPTY", STATE_RANGE, Alignment.LEFT), AnsiColor.ANSI_RED))); } if (online) { try { printed |= print(remote, StringProcessor.fillWithSpaces("Synchronization", LABEL_RANGE, Alignment.RIGHT) + " " + check(remote.requestData(), delayTime)); } catch (CouldNotPerformException e) { countError(); printed |= print(remote, StringProcessor.fillWithSpaces("Synchronization", LABEL_RANGE, Alignment.RIGHT) + " " + AnsiColor.colorize( StringProcessor.fillWithSpaces("CANCELED", STATE_RANGE, Alignment.LEFT), AnsiColor.ANSI_RED)); } } // add new line separator for better overview if (printed) { System.out.println(); } return printed; }
From source file:com.vmware.bdd.utils.CommonUtil.java
public static Object waitForThreadResult(Future<?> result, int waitTime) { for (int i = 0; i < waitTime; i++) { try {//from ww w. j a v a 2 s . c o m if (result.isDone()) { return result.get(); } // sleep 1 second here Thread.sleep(1000); } catch (Exception e) { logger.error("Unexpected error occurred with threading."); } } // time out now return null; }
From source file:microsoft.exchange.webservices.data.misc.AsyncCallbackImplementation.java
@Override public Object processMe(Future<?> task) { LOG.debug("In Async Callback" + task.isDone()); return null; }
From source file:gobblin.eventhub.writer.BatchedEventhubDataWriterTest.java
@Test public void testBufferedRecords() throws IOException, InterruptedException { // mock buffered async data writer Properties props = new Properties(); EventhubDataWriter eventhubDataWriter = Mockito.spy(new EventhubDataWriter(props, mockHttpClient)); EventhubBatchAccumulator accumulator = new EventhubBatchAccumulator(props); BatchedEventhubDataWriter dataWriter = new BatchedEventhubDataWriter(accumulator, eventhubDataWriter); Mockito.doNothing().when(eventhubDataWriter).refreshSignature(); // mock record and callback WriteCallback callback = mock(WriteCallback.class); List<Future<WriteResponse>> futures = new LinkedList<>(); int totalTimes = 500; try {/*from w w w. jav a2 s. c o m*/ for (int i = 0; i < totalTimes; ++i) { String record = "abcdefgh"; futures.add(dataWriter.write(record, callback)); } dataWriter.flush(); } finally { dataWriter.close(); } // verify all the callbacks are invoked verify(callback, times(totalTimes)).onSuccess(isA(WriteResponse.class)); verify(callback, never()).onFailure(isA(Exception.class)); // verify all the futures are completed for (Future future : futures) { Assert.assertTrue(future.isDone(), "Future should be done"); } }
From source file:gobblin.eventhub.writer.BufferedAsyncDataWriterTest.java
@Test public void testBufferedRecords() throws IOException, InterruptedException { // mock buffered async data writer Properties props = new Properties(); EventhubDataWriter eventhubDataWriter = Mockito.spy(new EventhubDataWriter(props, mockHttpClient)); EventhubBatchAccumulator accumulator = new EventhubBatchAccumulator(); BufferedAsyncDataWriter dataWriter = new BufferedAsyncDataWriter(accumulator, eventhubDataWriter); Mockito.doNothing().when(eventhubDataWriter).refreshSignature(); // mock record and callback WriteCallback callback = mock(WriteCallback.class); List<Future<RecordMetadata>> futures = new LinkedList<>(); int totalTimes = 500; try {//w ww .jav a 2 s . co m for (int i = 0; i < totalTimes; ++i) { String record = "abcdefgh"; futures.add(dataWriter.write(record, callback)); } dataWriter.flush(); } finally { dataWriter.close(); } // verify all the callbacks are invoked verify(callback, times(totalTimes)).onSuccess(isA(WriteResponse.class)); verify(callback, never()).onFailure(isA(Exception.class)); // verify all the futures are completed for (Future future : futures) { Assert.assertTrue(future.isDone(), "Future should be done"); } }
From source file:cz.muni.fi.mir.services.TaskServiceImpl.java
@Override public List<TaskStatus> getTasks() { List<TaskStatus> statuses = new ArrayList<>(); for (Future<TaskStatus> future : entries.keySet()) { try {/* ww w .j a va 2 s .c o m*/ if (future.isDone()) { statuses.add(0, future.get()); } else { statuses.add(0, entries.get(future).getStatus()); } } catch (InterruptedException e) { logger.warn("Task was interrupted.", e); } catch (ExecutionException e) { logger.warn("Task threw exception.", e); } } return statuses; }
From source file:eu.europa.ec.fisheries.uvms.plugins.ais.service.AisService.java
@PreDestroy public void destroy() { if (connection != null) { connection.close();// www .ja v a 2 s . c o m } Iterator<Future<Long>> processIterator = processes.iterator(); while (processIterator.hasNext()) { Future<Long> process = processIterator.next(); if (process.isDone() || process.isCancelled()) { processIterator.remove(); } else { process.cancel(true); } } }
From source file:org.apache.olingo.fit.proxy.AsyncTestITCase.java
@Test public void updateEntity() throws Exception { final String randomFirstName = RandomStringUtils.random(10, "abcedfghijklmnopqrstuvwxyz"); final Person person = container.getPeople().getByKey(1); person.setFirstName(randomFirstName); final Future<Void> futureFlush = container.flushAsync(); assertNotNull(futureFlush);/* w ww. j a v a 2 s . c o m*/ while (!futureFlush.isDone()) { Thread.sleep(1000L); } final Future<? extends Person> futurePerson = container.getPeople().getByKey(1).loadAsync(); assertEquals(randomFirstName, futurePerson.get().getFirstName()); }
From source file:gateway.test.UtilTests.java
/** * Initialize mock objects./*w ww .j a v a 2s. com*/ */ @Before public void setup() { MockitoAnnotations.initMocks(this); // Mock the Kafka response that Producers will send. This will always // return a Future that completes immediately and simply returns true. when(producer.send(isA(ProducerRecord.class))).thenAnswer(new Answer<Future<Boolean>>() { @Override public Future<Boolean> answer(InvocationOnMock invocation) throws Throwable { Future<Boolean> future = mock(FutureTask.class); when(future.isDone()).thenReturn(true); when(future.get()).thenReturn(true); return future; } }); }