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.chinamobile.bcbsp.comm.CommunicatorNew.java

private void clearSendMigrateVertexPool() {
    try {//from   w  w  w  . j  a  v a 2s.c  om
        // Iterator it = this.sendMssgResult.keySet().iterator();
        // while(it.hasNext()){
        // LOG.info("clearSendMssgPool Test! "+it.toString());
        // }sendVertexResult : HashMap<Integer, Future<Boolean>>
        for (Future<Boolean> ele : this.sendVertexResult.values()) {
            if (!ele.isDone()) {
                ele.get();
            }
        }
        this.sendVertexResult.clear();
    } catch (Exception e) {
        LOG.error("<clearSendVertexResult>" + e);
        throw new RuntimeException("<clearSendVertexResult>", e);
    }
}

From source file:org.cleverbus.component.externalcall.ExternalCallComponentTest.java

private Future<String> getStringBodyFuture(final Future<Exchange> reply) {
    return new Future<String>() {
        @Override//from  w ww . java2  s.c o  m
        public boolean cancel(boolean mayInterruptIfRunning) {
            return reply.cancel(mayInterruptIfRunning);
        }

        @Override
        public boolean isCancelled() {
            return reply.isCancelled();
        }

        @Override
        public boolean isDone() {
            return reply.isDone();
        }

        @Override
        public String get() throws InterruptedException, ExecutionException {
            return getReplyString(reply.get());
        }

        @Override
        public String get(long timeout, TimeUnit unit)
                throws InterruptedException, ExecutionException, TimeoutException {
            return getReplyString(reply.get(timeout, unit));
        }

        private String getReplyString(Exchange exchange) throws InterruptedException, ExecutionException {
            throwExceptionOptionally(exchange.getProperty(Exchange.EXCEPTION_CAUGHT, Exception.class));
            throwExceptionOptionally(exchange.getException());
            return exchange.getOut().getBody(String.class);
        }

        private void throwExceptionOptionally(Exception exc) throws InterruptedException, ExecutionException {
            if (exc != null) {
                if (exc instanceof InterruptedException) {
                    throw (InterruptedException) exc;
                } else if (exc instanceof ExecutionException) {
                    throw (ExecutionException) exc;
                } else {
                    throw new ExecutionException(exc);
                }
            }
        }
    };
}

From source file:com.mirth.connect.plugins.datapruner.DataPrunerTest.java

@Test
@Ignore//from w  ww .j  a  va 2 s  . com
public final void testConcurrency() throws Exception {
    /*
     * To run this concurrency test, you must setup a "reader" channel through the
     * administrator, that routes messages to other channels that will be pruned. Then specify
     * the ids of those channels below.
     */
    final String readerChannelId = "f7158274-8692-4e53-9d17-db732c3346b8";
    ExecutorService executor = Executors.newSingleThreadExecutor();
    TestUtils.startMirthServer(15000);

    DataPruner pruner = new DataPruner();
    pruner.setBlockSize(1);
    pruner.setStrategy(Strategy.INCLUDE_LIST);
    pruner.setRetryCount(0);

    TestUtils.deleteAllMessages(readerChannelId);
    TestUtils.deleteAllMessages("0831345e-bbe0-4d62-8f2d-c65280bd479b");
    TestUtils.deleteAllMessages("b2e28f1b-d867-435a-a5f6-3b33d5261e66");

    // send messages into the test channel on a separate thread
    Future<Void> future = executor.submit(new Callable<Void>() {
        @Override
        public Void call() throws Exception {
            EngineController engineController = ControllerFactory.getFactory().createEngineController();
            logger.info("Sending messages");

            for (int i = 0; i < 100000; i++) {
                logger.info("sending message #" + i);
                engineController.dispatchRawMessage(readerChannelId,
                        new RawMessage(TestUtils.TEST_HL7_MESSAGE));
            }

            logger.info("Finished sending messages");
            return null;
        }
    });

    logger.info("Executing pruner");

    // run the pruner while messages are processing
    while (!future.isDone()) {
        pruner.run();
        Thread.sleep(2000);
    }

    logger.info("Test completed");
}

From source file:com.chinamobile.bcbsp.comm.CommunicatorNew.java

@Override
public void sendMigrateMessage(IMessage msg, int DstPartition, int migrateSuperstepCounter) throws IOException {
    msg.setDstPartition(DstPartition);//from w  w  w . j  a va2 s  .  co  m
    int bucketID = Constants.PEER_COMPUTE_BUCK_ID;
    // msg.setMessageId(Constants.DEFAULT_PEER_DST_MESSSAGE_ID);
    // The destination partition is just in this staff.
    switch (messageManager.outgoAMessage(Constants.PEER_COMPUTE_BUCK_ID, msg)) {
    case MetaDataOfMessage.BufferStatus.NORMAL:
        break;
    case MetaDataOfMessage.BufferStatus.SPILL:
        Future<Boolean> result = sendMssgResult.get(bucketID);
        if (result != null && !result.isDone()) {
            try {
                result.get();
            } catch (Exception e) {
                throw new RuntimeException("<sendMessage>--<SendThread>", e);
            }
        }
        startSendMessageThread(bucketID, migrateSuperstepCounter);
        break;
    default:
        LOG.error("<Controll Message Sending Error>" + "<SuperStep>" + "<DestPartition>" + "<Bucket>");
    }
    // MetaDataOfMessage.SENDMSGCOUNTER++;
}

From source file:com.chinamobile.bcbsp.comm.CommunicatorNew.java

@Override
public void sendPartition(IMessage msg) throws IOException {
    int dstPartitonID = Integer.parseInt(msg.getDstVertexID());
    msg.setDstPartition(dstPartitonID);//from   ww w. j  a  v  a  2 s  .c om
    int bucketID = Constants.PEER_COMPUTE_BUCK_ID;
    msg.setMessageId(Constants.DEFAULT_PEER_DST_MESSSAGE_ID);
    // The destination partition is just in this staff.
    switch (messageManager.outgoAMessage(Constants.PEER_COMPUTE_BUCK_ID, msg)) {
    case MetaDataOfMessage.BufferStatus.NORMAL:
        break;
    case MetaDataOfMessage.BufferStatus.SPILL:
        Future<Boolean> result = sendMssgResult.get(bucketID);
        if (result != null && !result.isDone()) {
            try {
                result.get();
            } catch (Exception e) {
                throw new RuntimeException("<sendMessage>--<SendThread>", e);
            }
        }
        startSendMessageThread(bucketID, this.superstepCounter);
        break;
    default:
        LOG.error("<Controll Message Sending Error>" + "<SuperStep>" + "<DestPartition>" + "<Bucket>");
    }
    MetaDataOfMessage.SENDMSGCOUNTER++;
}

From source file:org.orekit.bodies.CelestialBodyFactoryTest.java

private void checkMultiThread(final int threads, final int runs) throws OrekitException {

    final AtomicReference<OrekitException> caught = new AtomicReference<OrekitException>();
    ExecutorService executorService = Executors.newFixedThreadPool(threads);

    List<Future<?>> results = new ArrayList<Future<?>>();
    for (int i = 0; i < threads; i++) {
        Future<?> result = executorService.submit(new Runnable() {
            public void run() {
                try {
                    for (int run = 0; run < runs; run++) {
                        CelestialBody mars = CelestialBodyFactory.getBody(CelestialBodyFactory.MARS);
                        Assert.assertNotNull(mars);
                        CelestialBodyFactory.clearCelestialBodyLoaders();
                    }/*  www. j  a va2s. c  o  m*/
                } catch (OrekitException oe) {
                    caught.set(oe);
                }
            }
        });
        results.add(result);
    }

    try {
        executorService.shutdown();
        executorService.awaitTermination(5, TimeUnit.SECONDS);
    } catch (InterruptedException ie) {
        Assert.fail(ie.getLocalizedMessage());
    }

    for (Future<?> result : results) {
        Assert.assertTrue("Not all threads finished -> possible deadlock", result.isDone());
    }

    if (caught.get() != null) {
        throw caught.get();
    }
}

From source file:com.rapid7.diskstorage.dynamodb.DynamoDBDelegate.java

public void parallelMutate(List<MutateWorker> workers) throws BackendException {
    CompletionService<Void> completion = new ExecutorCompletionService<>(clientThreadPool);
    List<Future<Void>> futures = Lists.newLinkedList();
    for (MutateWorker worker : workers) {
        futures.add(completion.submit(worker));
    }/*from   w  ww . j  ava2  s.c  om*/

    //block on the futures all getting or throwing instead of using a latch as i need to check future status anyway
    boolean interrupted = false;
    try {
        for (int i = 0; i < workers.size(); i++) {
            try {
                completion.take().get(); //Void
            } catch (InterruptedException e) {
                interrupted = true;
                // fail out because titan does not poll this thread for interrupted anywhere
                throw new BackendRuntimeException("was interrupted during parallelMutate");
            } catch (ExecutionException e) {
                throw unwrapExecutionException(e, MUTATE_ITEM);
            }
        }
    } finally {
        for (Future<Void> future : futures) {
            if (!future.isDone()) {
                future.cancel(interrupted /* mayInterruptIfRunning */);
            }
        }
        if (interrupted) {
            // set interrupted on this thread
            Thread.currentThread().interrupt();
        }
    }
}

From source file:com.mirth.connect.plugins.datapruner.test.DataPrunerTest.java

@Test
@Ignore/*from   w  ww .j  a va 2  s . c o m*/
public final void testConcurrency() throws Exception {
    /*
     * To run this concurrency test, you must setup a "reader" channel through the
     * administrator, that routes messages to other channels that will be pruned. Then specify
     * the ids of those channels below.
     */
    final String readerChannelId = "f7158274-8692-4e53-9d17-db732c3346b8";
    ExecutorService executor = Executors.newSingleThreadExecutor();
    TestUtils.startMirthServer(15000);

    DataPruner pruner = new DataPruner();
    pruner.setPrunerBlockSize(1);
    pruner.setRetryCount(0);

    TestUtils.deleteAllMessages(readerChannelId);
    TestUtils.deleteAllMessages("0831345e-bbe0-4d62-8f2d-c65280bd479b");
    TestUtils.deleteAllMessages("b2e28f1b-d867-435a-a5f6-3b33d5261e66");

    // send messages into the test channel on a separate thread
    Future<Void> future = executor.submit(new Callable<Void>() {
        @Override
        public Void call() throws Exception {
            EngineController engineController = ControllerFactory.getFactory().createEngineController();
            logger.info("Sending messages");

            for (int i = 0; i < 100000; i++) {
                logger.info("sending message #" + i);
                engineController.dispatchRawMessage(readerChannelId, new RawMessage(TestUtils.TEST_HL7_MESSAGE),
                        false, true);
            }

            logger.info("Finished sending messages");
            return null;
        }
    });

    logger.info("Executing pruner");

    // run the pruner while messages are processing
    while (!future.isDone()) {
        pruner.run();
        Thread.sleep(2000);
    }

    logger.info("Test completed");
}

From source file:com.chinamobile.bcbsp.comm.CommunicatorNew.java

@Override
public void send(IMessage msg) throws IOException {
    String vertexID = msg.getDstVertexID();
    int globalPartition = this.partitioner.getPartitionID(new Text(vertexID));
    int bucket = PartitionRule.localPartitionRule(vertexID);
    msg.setDstPartition(globalPartition);
    // The destination partition is just in this staff.
    int dstPartitionBucket = PartitionRule.getDestPartitionBucketId(globalPartition, bucket);
    switch (messageManager.outgoAMessage(dstPartitionBucket, msg)) {
    case MetaDataOfMessage.BufferStatus.NORMAL:
        break;//ww  w.j av  a 2 s  . c  om
    case MetaDataOfMessage.BufferStatus.SPILL:
        Future<Boolean> result = sendMssgResult.get(dstPartitionBucket);
        if (result != null && !result.isDone()) {
            try {
                result.get();
            } catch (Exception e) {
                throw new RuntimeException("<sendMessage>--<SendThread>", e);
            }
        }
        startSendMessageThread(dstPartitionBucket, this.superstepCounter);
        break;
    default:
        LOG.error("<Controll Message Sending Error>" + "<SuperStep>" + "<DestPartition>" + "<Bucket>");
    }
    MetaDataOfMessage.SENDMSGCOUNTER++;
}

From source file:com.cloudera.director.azure.compute.provider.AzureComputeProviderHelper.java

/**
 * Poll pending tasks till all tasks are complete or timeout.
 * Azure platform operation can range from minutes to one hour.
 *
 * @param tasks            set of submitted tasks
 * @param durationInSecond overall timeout period
 * @param intervalInSecond poll interval
 * @param failedContexts   set of failed task contexts. This list contains all the contexts of
 *                         submitted tasks. Context of a successful task is removed from this
 *                         set. When this call returns the element in this set are the contexts
 *                         of failed tasks.
 * @return number of successful tasks//from   w ww  . j  av  a2  s .c o m
 */
@SuppressWarnings("PMD.CollapsibleIfStatements")
public int pollPendingTasks(Set<Future<TaskResult>> tasks, int durationInSecond, int intervalInSecond,
        Set<ResourceContext> failedContexts) {
    Set<Future<TaskResult>> responses = new HashSet<>(tasks);
    int succeededCount = 0;
    int timerInMilliSec = durationInSecond * 1000;
    int intervalInMilliSec = intervalInSecond * 1000;

    try {
        while (timerInMilliSec > 0 && responses.size() > 0) {
            Set<Future<TaskResult>> dones = new HashSet<>();
            for (Future<TaskResult> task : responses) {
                try {
                    if (task.isDone()) {
                        dones.add(task);
                        TaskResult tr = task.get();
                        if (tr.isSuccessful()) {
                            succeededCount++;
                            // Remove successful contexts so that what remains are the failed contexts
                            if (failedContexts != null) {
                                if (!failedContexts.remove(tr.getContex())) {
                                    LOG.error(
                                            "ResourceContext {} does not exist in the submitted context list.",
                                            tr.getContex());
                                }
                            }
                        }
                    }
                } catch (ExecutionException e) {
                    LOG.error("Polling of pending tasks encountered an error: ", e);
                }
            }
            responses.removeAll(dones);

            Thread.sleep(intervalInMilliSec);

            timerInMilliSec = timerInMilliSec - intervalInMilliSec;
            LOG.debug("Polling pending tasks: remaining time = " + timerInMilliSec / 1000 + " seconds.");
        }
    } catch (InterruptedException e) {
        LOG.error("Polling of pending tasks was interrupted.", e);
        shutdownTaskRunnerService();
    }

    // Terminate all tasks if we timed out.
    if (timerInMilliSec <= 0 && responses.size() > 0) {
        shutdownTaskRunnerService();
    }

    // Always return the succeeded task count and let the caller decide if any resources needs to be
    // cleaned up
    return succeededCount;
}