Example usage for java.util.concurrent Future isDone

List of usage examples for java.util.concurrent Future isDone

Introduction

In this page you can find the example usage for java.util.concurrent Future isDone.

Prototype

boolean isDone();

Source Link

Document

Returns true if this task completed.

Usage

From source file:com.vmware.bdd.service.resmgmt.impl.VcInventorySyncService.java

private void work(ThreadPoolTaskExecutor es, List<AbstractSyncVcResSP> syncSps)
        throws ExecutionException, InterruptedException {
    List<Future<List<AbstractSyncVcResSP>>> resultList = submit(es, syncSps);

    while (resultList.size() > 0) {
        Thread.sleep(waitMilliSecs);

        List<AbstractSyncVcResSP> newTaskList = new ArrayList<>();
        for (Iterator<Future<List<AbstractSyncVcResSP>>> resultIterator = resultList.iterator(); resultIterator
                .hasNext();) {/*from ww  w. j a v  a  2s .c om*/
            Future<List<AbstractSyncVcResSP>> result = resultIterator.next();
            if (result.isDone()) {
                counters.decreasePendingRefresh();
                counters.increaseFinishedRefresh();

                newTaskList.addAll(result.get());
                resultIterator.remove();
            }
        }

        resultList.addAll(submit(es, newTaskList));

        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("remain refresh task count: " + resultList.size());
        }
    }
}

From source file:org.springsource.ide.eclipse.boot.maven.analyzer.server.AetherialController.java

/**
 * Helper method to send a 'Future' as a response to the client. 
 * If the future is 'done' actual content (or error) is sent. Otherwise
 * a 'try later' result is sent instead.
 *//*from w  ww.ja  v a 2  s .c  om*/
private void sendResponse(HttpServletResponse resp, Future<byte[]> result)
        throws IOException, UnsupportedEncodingException {
    if (!result.isDone()) {
        //Return something quickly to let client know we are working on their request but
        // it may be a while.
        resp.setStatus(HttpServletResponse.SC_ACCEPTED);
        resp.setContentType("text/plain");
        resp.setCharacterEncoding("utf8");
        resp.getWriter().println("I'm working on it... ask me again later");
    } else {
        //Done: could be a actual result or an error
        try {
            byte[] resultData = result.get(); //this will throw in case of an error in processing.
            resp.setStatus(HttpServletResponse.SC_OK);
            //resp.setContentType(contentType);
            //resp.setCharacterEncoding("utf8");
            resp.getOutputStream().write(resultData);
        } catch (Exception e) {
            resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            resp.setContentType("text/plain");
            resp.setCharacterEncoding("utf8");
            e.printStackTrace(new PrintStream(resp.getOutputStream(), true, "utf8"));
        }
    }
}

From source file:gobblin.eventhub.writer.EventhubDataWriterTest.java

@Test
public void testSingleBatch() {
    // mock eventhub data writer
    Properties props = new Properties();
    EventhubDataWriter eventhubDataWriter = Mockito.spy(new EventhubDataWriter(props, mockHttpClient));
    Mockito.doNothing().when(eventhubDataWriter).refreshSignature();

    List<String> records = new LinkedList<>();
    for (int i = 0; i < 50; ++i)
        records.add(new String("abcdefgh"));

    Batch<String> batch = mock(Batch.class);
    WriteCallback callback = mock(WriteCallback.class);
    Mockito.when(batch.getRecords()).thenReturn(records);

    Future<WriteResponse> future = eventhubDataWriter.write(batch, callback);
    verify(callback, times(1)).onSuccess(isA(WriteResponse.class));
    verify(callback, never()).onFailure(isA(Exception.class));
    Assert.assertTrue(future.isDone(), "Future should be done");
}

From source file:org.apache.hadoop.fs.nfs.stream.NFSBufferedOutputStream.java

private void checkOngoing() throws IOException {
    if (ongoing.size() >= 64) {
        for (Iterator<Future<Write>> iter = ongoing.iterator(); iter.hasNext();) {
            Future<Write> f = iter.next();
            if (!f.isDone()) {
                try {
                    f.get();/*w w w .  j  a  v  a2 s  .  c o m*/
                    iter.remove();
                } catch (InterruptedException interrupted) {
                    // Ignore
                } catch (ExecutionException execution) {
                    throw new IOException("Write back call failed", execution);
                }
            }
        }
    }
}

From source file:com.ejisto.modules.executor.TaskManager.java

private ExecutionState getExecutionState(Future<?> future) {
    if (future.isCancelled()) {
        return ExecutionState.CANCELED;
    }/*from www.j  a  va  2 s.  c o m*/
    if (future.isDone()) {
        return ExecutionState.DONE;
    }
    return ExecutionState.RUNNING;
}

From source file:org.openspaces.itest.remoting.simple.plain.SimpleRemotingTests.java

@Test
public void testAsyncExecutionIsDone() throws InterruptedException, ExecutionException {
    Future result = simpleService.asyncSay("test");
    while (!result.isDone()) {
        Thread.sleep(1000);/*from   w w w  . j  a v a 2 s.  co  m*/
    }
    assertEquals("SAY test", result.get());
}

From source file:gateway.test.DeploymentTests.java

/**
 * Initialize mock objects./*from w  ww.j a v  a  2  s  .  c  om*/
 */
@Before
public void setup() {
    MockitoAnnotations.initMocks(this);
    MockitoAnnotations.initMocks(gatewayUtil);

    // Mock a common error we can use to test
    mockError = new ErrorResponse("Error!", "Test");

    // Mock a user
    user = new JMXPrincipal("Test User");

    // Mock some deployment
    mockDeployment = new Deployment("123456", "654321", "localhost", "8080", "layer",
            "http://localhost:8080/layer?request=GetCapabilities");

    // 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;
        }
    });

    when(gatewayUtil.getErrorResponse(anyString())).thenCallRealMethod();
}

From source file:gateway.test.JobTests.java

/**
 * Initialize mock objects.// w  w w .  j a v  a  2s.  c om
 */
@Before
public void setup() {
    MockitoAnnotations.initMocks(this);
    MockitoAnnotations.initMocks(gatewayUtil);

    // Mock a common error we can use to test
    mockError = new ErrorResponse("Job Not Found", "Gateway");
    mockJobError = new ResponseEntity<PiazzaResponse>(new JobErrorResponse("1234", "Job Not Found", "Gateway"),
            HttpStatus.NOT_FOUND);

    // Mock a Job
    mockJob = new Job();
    mockJob.setJobId("123456");
    mockJob.jobType = new RepeatJob("654321");
    mockJob.progress = new JobProgress(50);
    mockJob.createdBy = "Test User 2";
    mockJob.status = StatusUpdate.STATUS_RUNNING;

    // Mock a user
    user = new JMXPrincipal("Test User");

    // 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;
        }
    });

    when(gatewayUtil.getErrorResponse(anyString())).thenCallRealMethod();
}

From source file:com.amazon.alexa.avs.NotificationManager.java

private void cleanUpIndicatorFutures() {
    synchronized (indicatorFutures) {
        Iterator<Future<?>> it = indicatorFutures.iterator();
        while (it.hasNext()) {
            Future<?> f = it.next();
            if (f.isDone() || f.isCancelled()) {
                it.remove();//from w w w. jav a 2s . c o m
            }
        }
    }
}

From source file:aos.camel.CamelFutureDoneTest.java

@Test
public void testFutureDone() throws Exception {
    // now send the message to the endpoint in async manner
    // and get the Future handle back so we can later get the result
    LOG.info("Submitting task to Camel");
    Future<String> future = template.asyncRequestBody("seda:quote", "Hello Camel", String.class);
    LOG.info("Task submitted and we got a Future handle");

    // test when we are done
    boolean done = false;
    while (!done) {
        done = future.isDone();
        LOG.info("Is the task done? " + done);
        if (!done) {
            Thread.sleep(2000);//from   w ww  . j a v  a 2s  . c om
        }
    }

    // and get the answer
    String answer = future.get();
    LOG.info("The answer is: " + answer);
}