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:ly.count.android.api.ConnectionQueueTests.java

public void testTick_storeHasConnectionsAndFutureIsDone() {
    final Future<?> mockFuture = mock(Future.class);
    when(mockFuture.isDone()).thenReturn(true);
    connQ.setConnectionProcessorFuture(mockFuture);
    final Future mockFuture2 = mock(Future.class);
    when(connQ.getExecutor().submit(any(ConnectionProcessor.class))).thenReturn(mockFuture2);
    connQ.tick();//from ww w  .j a v  a 2s  .c  o  m
    verify(connQ.getExecutor()).submit(any(ConnectionProcessor.class));
    assertSame(mockFuture2, connQ.getConnectionProcessorFuture());
}

From source file:org.apache.hadoop.yarn.server.nodemanager.containermanager.localizer.ContainerLocalizer.java

/**
 * Create the payload for the HeartBeat. Mainly the list of
 * {@link LocalResourceStatus}es//from   w w w . j a va 2s .  c o m
 * 
 * @return a {@link LocalizerStatus} that can be sent via heartbeat.
 * @throws InterruptedException
 */
private LocalizerStatus createStatus() throws InterruptedException {
    final List<LocalResourceStatus> currentResources = new ArrayList<LocalResourceStatus>();
    // TODO: Synchronization??
    for (Iterator<LocalResource> i = pendingResources.keySet().iterator(); i.hasNext();) {
        LocalResource rsrc = i.next();
        LocalResourceStatus stat = recordFactory.newRecordInstance(LocalResourceStatus.class);
        stat.setResource(rsrc);
        Future<Path> fPath = pendingResources.get(rsrc);
        if (fPath.isDone()) {
            try {
                Path localPath = fPath.get();
                stat.setLocalPath(URL.fromPath(localPath));
                stat.setLocalSize(FileUtil.getDU(new File(localPath.getParent().toUri())));
                stat.setStatus(ResourceStatusType.FETCH_SUCCESS);
            } catch (ExecutionException e) {
                stat.setStatus(ResourceStatusType.FETCH_FAILURE);
                stat.setException(SerializedException.newInstance(e.getCause()));
            } catch (CancellationException e) {
                stat.setStatus(ResourceStatusType.FETCH_FAILURE);
                stat.setException(SerializedException.newInstance(e));
            }
            // TODO shouldn't remove until ACK
            i.remove();
        } else {
            stat.setStatus(ResourceStatusType.FETCH_PENDING);
        }
        currentResources.add(stat);
    }
    LocalizerStatus status = recordFactory.newRecordInstance(LocalizerStatus.class);
    status.setLocalizerId(localizerId);
    status.addAllResources(currentResources);
    return status;
}

From source file:com.nps.micro.UsbService.java

@Override
public void onDestroy() {
    closeMicrocontrollers();//from  w w w.j  av  a 2 s .  co m
    statusThread.finalize();
    executorService.shutdown();
    for (@SuppressWarnings("rawtypes")
    Future future : futures) {
        if (!future.isDone()) {
            future.cancel(false);
        }
    }
    try {
        executorService.awaitTermination(10, TimeUnit.MINUTES);
    } catch (InterruptedException e) {
        Log.e(TAG, "Couldn't finalize tasks cause: " + e.getMessage());
    }
    notificationManager.cancel(NOTIFICATION);
    isRunning = false;
    super.onDestroy();
}

From source file:gateway.test.DataTests.java

/**
 * Initialize mock objects./*from   w  w  w. java 2 s. c o m*/
 */
@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 some Data that we can use in our test cases.
    mockData = new DataResource();
    mockData.dataId = "DataID";
    mockData.dataType = new TextDataType();
    ((TextDataType) mockData.dataType).content = "MockData";
    mockData.metadata = new ResourceMetadata();
    mockData.metadata.setName("Test Data");

    // 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:gridool.processors.job.GridJobWorker.java

private void cancelRemainingTasks(final Map<String, Pair<GridTask, List<Future<?>>>> taskMap) {
    for (final Pair<GridTask, List<Future<?>>> entry : taskMap.values()) {
        final List<Future<?>> futures = entry.getSecond();
        assert (futures != null);
        for (final Future<?> future : futures) {
            if (!future.isDone()) {
                // TODO send cancel request
                future.cancel(true);/*from   w w w  . ja va 2  s .com*/
            }
        }
    }
}

From source file:eu.edisonproject.training.wsd.WikipediaOnline.java

private Map<CharSequence, List<CharSequence>> getCategories(Set<Term> terms)
        throws MalformedURLException, InterruptedException, ExecutionException {
    int maxT = 2;
    BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue(maxT);
    ExecutorService pool = new ThreadPoolExecutor(maxT, maxT, 500L, TimeUnit.MICROSECONDS, workQueue);

    //        ExecutorService pool = new ThreadPoolExecutor(maxT, maxT,
    //                5000L, TimeUnit.MILLISECONDS,
    //                new ArrayBlockingQueue<>(maxT, true), new ThreadPoolExecutor.CallerRunsPolicy());
    Map<CharSequence, List<CharSequence>> cats = new HashMap<>();
    Set<Future<Map<CharSequence, List<CharSequence>>>> set = new HashSet<>();
    for (Term t : terms) {
        URL url = new URL(PAGE + "?action=query&format=json&prop=categories&pageids=" + t.getUid());
        LOGGER.log(Level.FINE, url.toString());
        WikiRequestor req = new WikiRequestor(url, t.getUid().toString(), 0);
        Future<Map<CharSequence, List<CharSequence>>> future = pool.submit(req);
        set.add(future);// w ww  .  j  av a 2  s  .  c  o m
    }
    pool.shutdown();

    for (Future<Map<CharSequence, List<CharSequence>>> future : set) {
        while (!future.isDone()) {
            //                LOGGER.log(Level.INFO, "Task is not completed yet....");
            Thread.currentThread().sleep(10);
        }
        Map<CharSequence, List<CharSequence>> c = future.get();
        if (c != null) {
            cats.putAll(c);
        }
    }

    return cats;
}

From source file:nl.uva.sne.disambiguators.WikipediaOnline.java

private Map<String, List<String>> getCategories(Set<Term> terms)
        throws MalformedURLException, InterruptedException, ExecutionException {
    int maxT = 3;
    BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue(maxT);
    ExecutorService pool = new ThreadPoolExecutor(maxT, maxT, 500L, TimeUnit.MICROSECONDS, workQueue);

    //        ExecutorService pool = new ThreadPoolExecutor(maxT, maxT,
    //                5000L, TimeUnit.MILLISECONDS,
    //                new ArrayBlockingQueue<>(maxT, true), new ThreadPoolExecutor.CallerRunsPolicy());
    Map<String, List<String>> cats = new HashMap<>();
    Set<Future<Map<String, List<String>>>> set = new HashSet<>();
    int count = 0;
    for (Term t : terms) {
        URL url = new URL(page + "?action=query&format=json&prop=categories&pageids=" + t.getUID());
        System.err.println(url);//from   ww w. j a  v  a 2  s .  co m
        WikiRequestor req = new WikiRequestor(url, t.getUID(), 0);
        Future<Map<String, List<String>>> future = pool.submit(req);
        set.add(future);
    }
    pool.shutdown();

    for (Future<Map<String, List<String>>> future : set) {
        while (!future.isDone()) {
            //                Logger.getLogger(WikipediaOnline.class.getName()).log(Level.INFO, "Task is not completed yet....");
            Thread.currentThread().sleep(10);
        }
        Map<String, List<String>> c = future.get();
        if (c != null) {
            cats.putAll(c);
        }
    }

    return cats;
}

From source file:org.jaqpot.core.service.client.jpdi.JPDIClientImpl.java

@Override
public boolean cancel(String taskId) {
    Future future = futureMap.get(taskId);
    if (future != null && !future.isCancelled() && !future.isDone()) {
        future.cancel(true);//  w  w w.ja va2s  .  c o m
        return true;
    }
    return false;
}

From source file:org.apache.hadoop.yarn.server.nodemanager.containermanager.localizer.TestContainerLocalizer.java

@SuppressWarnings("unchecked") // mocked generics
private ContainerLocalizer setupContainerLocalizerForTest() throws Exception {
    // don't actually create dirs
    doNothing().when(spylfs).mkdir(isA(Path.class), isA(FsPermission.class), anyBoolean());

    Configuration conf = new Configuration();
    FileContext lfs = FileContext.getFileContext(spylfs, conf);
    localDirs = new ArrayList<Path>();
    for (int i = 0; i < 4; ++i) {
        localDirs.add(lfs.makeQualified(new Path(basedir, i + "")));
    }/*from w w  w  .  j  a  va  2  s .c  om*/
    RecordFactory mockRF = getMockLocalizerRecordFactory();
    ContainerLocalizer concreteLoc = new ContainerLocalizer(lfs, appUser, appId, containerId, localDirs, mockRF,
            appUserFolder);
    ContainerLocalizer localizer = spy(concreteLoc);

    // return credential stream instead of opening local file
    random = new Random();
    long seed = random.nextLong();
    System.out.println("SEED: " + seed);
    random.setSeed(seed);
    DataInputBuffer appTokens = createFakeCredentials(random, 10);
    tokenPath = lfs.makeQualified(new Path(String.format(ContainerLocalizer.TOKEN_FILE_NAME_FMT, containerId)));
    doReturn(new FSDataInputStream(new FakeFSDataInputStream(appTokens))).when(spylfs).open(tokenPath);
    nmProxy = mock(LocalizationProtocol.class);
    doReturn(nmProxy).when(localizer).getProxy(nmAddr);
    doNothing().when(localizer).sleep(anyInt());

    // return result instantly for deterministic test
    ExecutorService syncExec = mock(ExecutorService.class);
    CompletionService<Path> cs = mock(CompletionService.class);
    when(cs.submit(isA(Callable.class))).thenAnswer(new Answer<Future<Path>>() {
        @Override
        public Future<Path> answer(InvocationOnMock invoc) throws Throwable {
            Future<Path> done = mock(Future.class);
            when(done.isDone()).thenReturn(true);
            FakeDownload d = (FakeDownload) invoc.getArguments()[0];
            when(done.get()).thenReturn(d.call());
            return done;
        }
    });
    doReturn(syncExec).when(localizer).createDownloadThreadPool();
    doReturn(cs).when(localizer).createCompletionService(syncExec);

    return localizer;
}

From source file:org.apache.solr.schema.ManagedIndexSchema.java

/**
 * Block up to a specified maximum time until we see agreement on the schema
 * version in ZooKeeper across all replicas for a collection.
 *//*w  ww .  j a v a  2  s .com*/
public static void waitForSchemaZkVersionAgreement(String collection, String localCoreNodeName,
        int schemaZkVersion, ZkController zkController, int maxWaitSecs) {
    RTimer timer = new RTimer();

    // get a list of active replica cores to query for the schema zk version (skipping this core of course)
    List<GetZkSchemaVersionCallable> concurrentTasks = new ArrayList<>();
    for (String coreUrl : getActiveReplicaCoreUrls(zkController, collection, localCoreNodeName))
        concurrentTasks.add(new GetZkSchemaVersionCallable(coreUrl, schemaZkVersion));
    if (concurrentTasks.isEmpty())
        return; // nothing to wait for ...

    log.info("Waiting up to " + maxWaitSecs + " secs for " + concurrentTasks.size()
            + " replicas to apply schema update version " + schemaZkVersion + " for collection " + collection);

    // use an executor service to invoke schema zk version requests in parallel with a max wait time
    int poolSize = Math.min(concurrentTasks.size(), 10);
    ExecutorService parallelExecutor = ExecutorUtil.newMDCAwareFixedThreadPool(poolSize,
            new DefaultSolrThreadFactory("managedSchemaExecutor"));
    try {
        List<Future<Integer>> results = parallelExecutor.invokeAll(concurrentTasks, maxWaitSecs,
                TimeUnit.SECONDS);

        // determine whether all replicas have the update
        List<String> failedList = null; // lazily init'd
        for (int f = 0; f < results.size(); f++) {
            int vers = -1;
            Future<Integer> next = results.get(f);
            if (next.isDone() && !next.isCancelled()) {
                // looks to have finished, but need to check the version value too
                try {
                    vers = next.get();
                } catch (ExecutionException e) {
                    // shouldn't happen since we checked isCancelled
                }
            }

            if (vers == -1) {
                String coreUrl = concurrentTasks.get(f).coreUrl;
                log.warn("Core " + coreUrl + " version mismatch! Expected " + schemaZkVersion + " but got "
                        + vers);
                if (failedList == null)
                    failedList = new ArrayList<>();
                failedList.add(coreUrl);
            }
        }

        // if any tasks haven't completed within the specified timeout, it's an error
        if (failedList != null)
            throw new SolrException(ErrorCode.SERVER_ERROR,
                    failedList.size() + " out of " + (concurrentTasks.size() + 1)
                            + " replicas failed to update their schema to version " + schemaZkVersion
                            + " within " + maxWaitSecs + " seconds! Failed cores: " + failedList);

    } catch (InterruptedException ie) {
        log.warn("Core " + localCoreNodeName + " was interrupted waiting for schema version " + schemaZkVersion
                + " to propagate to " + concurrentTasks.size() + " replicas for collection " + collection);

        Thread.currentThread().interrupt();
    } finally {
        if (!parallelExecutor.isShutdown())
            parallelExecutor.shutdown();
    }

    log.info("Took {}ms for {} replicas to apply schema update version {} for collection {}", timer.getTime(),
            concurrentTasks.size(), schemaZkVersion, collection);
}