Example usage for java.util.concurrent FutureTask get

List of usage examples for java.util.concurrent FutureTask get

Introduction

In this page you can find the example usage for java.util.concurrent FutureTask get.

Prototype

public V get() throws InterruptedException, ExecutionException 

Source Link

Usage

From source file:gridool.construct.GridTaskAdapter.java

public final Serializable invokeTask() throws GridException {
    final FutureTask<Serializable> runningTask = new FutureTask<Serializable>(this);
    this.running = runningTask;
    runningTask.run();/*from ww w  .  j  a v  a2s .c  o m*/
    try {
        return runningTask.get();
    } catch (InterruptedException e) {
        LOG.warn("task canceled: " + getTaskId());
        throw TaskCancelException.getInstance();
    } catch (ExecutionException e) {
        throw new GridException(e);
    } finally {
        this.running = null;
    }
}

From source file:com.intuit.tank.perfManager.workLoads.JobManager.java

private void startTest(final JobInfo info) {
    LOG.info("Sending start command asynchronously.");
    Thread t = new Thread(new Runnable() {
        @Override/* w  w  w  .  ja v a 2 s .c o m*/
        public void run() {
            LOG.info(
                    "Sleeping for one minute before starting test to give time for all agents to download files.");
            try {
                Thread.sleep(60000);// sixty seconds
            } catch (InterruptedException e) {
                // ignore
            }
            try {
                LOG.info("Sending start commands on executer.");
                List<FutureTask<AgentData>> futures = new ArrayList<FutureTask<AgentData>>();
                for (AgentData agent : info.agentData) {
                    futures.add(sendCommand(agent, WatsAgentCommand.start, true));
                }
                LOG.info("waiting for agentFutures to return.");
                for (FutureTask<AgentData> future : futures) {
                    AgentData dataFuture = future.get();
                    if (dataFuture != null) {
                        // error happened. TODO: message system that agent did not start.
                        tracker.setStatus(crateFailureStatus(dataFuture));
                        tracker.stopJob(info.jobRequest.getId());
                    }
                }
                LOG.info("All agents received start command.");
            } catch (Exception e) {
                LOG.error("Error sending start: " + e, e);
                tracker.stopJob(info.jobRequest.getId());
            }

        }

    });
    t.setDaemon(true);
    t.start();
}

From source file:org.apache.hadoop.corona.TestMiniCoronaRunJob.java

public void testDiskLimit() throws Exception {
    LOG.info("Starting testDiskLimit");
    JobConf conf = new JobConf();
    conf.setInt(CoronaConf.NODE_RESERVED_DISK_GB, Integer.MAX_VALUE);
    corona = new MiniCoronaCluster.Builder().conf(conf).numTaskTrackers(2).build();
    final JobConf jobConf = corona.createJobConf();
    long start = System.currentTimeMillis();
    FutureTask<Boolean> task = submitSleepJobFutureTask(jobConf);
    checkTaskNotDone(task, 10);//from  w  w w.j  ava2  s  .  c o m
    NodeManager nm = corona.getClusterManager().getNodeManager();
    nm.getResourceLimit().setNodeReservedDiskGB(0);
    Assert.assertTrue(task.get());
    long end = System.currentTimeMillis();
    new ClusterManagerMetricsVerifier(corona.getClusterManager(), 1, 1, 1, 1, 1, 1, 0, 0).verifyAll();
    LOG.info("Time spent for testDiskLimit:" + (end - start));
}

From source file:org.apache.hadoop.corona.TestMiniCoronaRunJob.java

public void testMemoryLimit() throws Exception {
    LOG.info("Starting testMemoryLimit");
    JobConf conf = new JobConf();
    conf.setInt(CoronaConf.NODE_RESERVED_MEMORY_MB, Integer.MAX_VALUE);
    corona = new MiniCoronaCluster.Builder().conf(conf).numTaskTrackers(2).build();
    final JobConf jobConf = corona.createJobConf();
    long start = System.currentTimeMillis();
    FutureTask<Boolean> task = submitSleepJobFutureTask(jobConf);
    checkTaskNotDone(task, 10);/*  w w  w .j  ava  2  s  .  c om*/
    NodeManager nm = corona.getClusterManager().getNodeManager();
    nm.getResourceLimit().setNodeReservedMemoryMB(0);
    Assert.assertTrue(task.get());
    long end = System.currentTimeMillis();
    LOG.info("Task Done. Verifying");
    new ClusterManagerMetricsVerifier(corona.getClusterManager(), 1, 1, 1, 1, 1, 1, 0, 0).verifyAll();
    LOG.info("Time spent for testMemoryLimit:" + (end - start));
}

From source file:org.apache.cxf.dosgi.systests.common.AbstractListenerHookServiceListenerTest.java

private void verifyGreeterResponse(FutureTask<Map<GreetingPhrase, String>> task, Object mutex)
        throws Exception {
    Map<GreetingPhrase, String> greetings = null;
    synchronized (mutex) {
        while (task == null) {
            mutex.wait(500);//from  w  w w. ja va2s . co  m
        }
        greetings = task.get();
    }

    assertEquals("Fred", greetings.get(new GreetingPhrase("Hello")));
}

From source file:com.ciphertool.genetics.Population.java

/**
 * This method executes all the fitness evaluations concurrently.
 *///  ww  w . j  ava  2s  .  c  o m
private void doConcurrentFitnessEvaluations() {
    List<FutureTask<Double>> futureTasks = new ArrayList<FutureTask<Double>>();
    FutureTask<Double> futureTask = null;

    int evaluationCount = 0;
    for (Chromosome individual : individuals) {
        /*
         * Only evaluate individuals that have changed since the last
         * evaluation.
         */
        if (individual.isDirty()) {
            evaluationCount++;
            futureTask = new FutureTask<Double>(new EvaluatorTask(individual));
            futureTasks.add(futureTask);
            this.taskExecutor.execute(futureTask);
        }
    }
    log.debug("Evaluations carried out: " + evaluationCount);

    for (FutureTask<Double> future : futureTasks) {
        try {
            future.get();
        } catch (InterruptedException ie) {
            log.error("Caught InterruptedException while waiting for EvaluatorTask ", ie);
        } catch (ExecutionException ee) {
            log.error("Caught ExecutionException while waiting for EvaluatorTask ", ee);
        }
    }
}

From source file:com.ciphertool.genetics.algorithms.ConcurrentMultigenerationalGeneticAlgorithm.java

protected List<Chromosome> doConcurrentCrossovers(long pairsToCrossover, List<Chromosome> moms,
        List<Chromosome> dads) {
    List<FutureTask<List<Chromosome>>> futureTasks = new ArrayList<FutureTask<List<Chromosome>>>();
    FutureTask<List<Chromosome>> futureTask = null;

    Chromosome mom = null;//w w  w . j  a  va  2 s. c  o m
    Chromosome dad = null;

    /*
     * Execute each crossover concurrently. Parents should produce two
     * children, but this is not necessarily always guaranteed.
     */
    for (int i = 0; i < pairsToCrossover; i++) {
        mom = moms.get(i);
        dad = dads.get(i);

        futureTask = new FutureTask<List<Chromosome>>(new CrossoverTask(mom, dad));
        futureTasks.add(futureTask);
        this.taskExecutor.execute(futureTask);
    }

    List<Chromosome> childrenToAdd = new ArrayList<Chromosome>();
    /*
     * Add the result of each FutureTask to the population since it
     * represents a new child Chromosome.
     */
    for (FutureTask<List<Chromosome>> future : futureTasks) {
        try {
            /*
             * Add children after all crossover operations are completed so
             * that children are not inadvertently breeding immediately
             * after birth.
             */
            childrenToAdd.addAll(future.get());
        } catch (InterruptedException ie) {
            log.error("Caught InterruptedException while waiting for CrossoverTask ", ie);
        } catch (ExecutionException ee) {
            log.error("Caught ExecutionException while waiting for CrossoverTask ", ee);
        }
    }

    return childrenToAdd;
}

From source file:io.selendroid.ServerInstrumentation.java

private void runSynchronouslyOnUiThread(Runnable action) {
    FutureTask<Void> uiTask = new FutureTask<Void>(action, null);
    mainThreadExecutor.execute(uiTask);/*ww  w  .  j  av a 2  s. com*/
    try {
        uiTask.get();
    } catch (Exception e) {
        throw new AppCrashedException("Unhandled exception from application under test.", e);
    }
}

From source file:com.ciphertool.genetics.Population.java

public int breed(Integer maxIndividuals) {
    List<FutureTask<Chromosome>> futureTasks = new ArrayList<FutureTask<Chromosome>>();
    FutureTask<Chromosome> futureTask = null;

    int individualsAdded = 0;
    for (int i = this.individuals.size(); i < maxIndividuals; i++) {
        futureTask = new FutureTask<Chromosome>(new GeneratorTask());
        futureTasks.add(futureTask);//from   w  w  w. j  av  a 2s  .co  m

        this.taskExecutor.execute(futureTask);
    }

    for (FutureTask<Chromosome> future : futureTasks) {
        try {
            this.individuals.add(future.get());

            individualsAdded++;
        } catch (InterruptedException ie) {
            log.error("Caught InterruptedException while waiting for GeneratorTask ", ie);
        } catch (ExecutionException ee) {
            log.error("Caught ExecutionException while waiting for GeneratorTask ", ee);
        }
    }

    if (log.isDebugEnabled()) {
        log.debug("Added " + individualsAdded + " individuals to the population.");
    }

    return individualsAdded;
}

From source file:com.ciphertool.genetics.algorithms.ConcurrentBasicGeneticAlgorithm.java

@Override
public int crossover(int initialPopulationSize) {
    if (this.population.size() < 2) {
        log.info(//w  w w  . j a  va 2s  . co  m
                "Unable to perform crossover because there is only 1 individual in the population. Returning.");

        return 0;
    }

    long pairsToCrossover = Math.min((long) (initialPopulationSize * strategy.getCrossoverRate()),
            ((long) (this.population.size() / 2)));

    log.debug("Pairs to crossover: " + pairsToCrossover);

    Chromosome mom = null;
    Chromosome dad = null;
    int momIndex = -1;
    int dadIndex = -1;

    List<Chromosome> moms = new ArrayList<Chromosome>();
    List<Chromosome> dads = new ArrayList<Chromosome>();

    /*
     * We first remove all the parent Chromosomes since the children are
     * guaranteed to be at least as fit. This also prevents parents from
     * reproducing more than one time per generation.
     */
    for (int i = 0; i < pairsToCrossover; i++) {
        momIndex = this.population.selectIndex();
        moms.add(this.population.getIndividuals().get(momIndex));
        this.population.makeIneligibleForReproduction(momIndex);

        dadIndex = this.population.selectIndex();
        dads.add(this.population.getIndividuals().get(dadIndex));
        this.population.makeIneligibleForReproduction(dadIndex);
    }

    List<FutureTask<List<Chromosome>>> futureTasks = new ArrayList<FutureTask<List<Chromosome>>>();
    FutureTask<List<Chromosome>> futureTask = null;

    /*
     * Execute each crossover concurrently. Parents should produce two
     * children, but this is not necessarily always guaranteed.
     */
    for (int i = 0; i < pairsToCrossover; i++) {
        mom = moms.get(i);
        dad = dads.get(i);

        futureTask = new FutureTask<List<Chromosome>>(new CrossoverTask(mom, dad));
        futureTasks.add(futureTask);
        this.taskExecutor.execute(futureTask);
    }

    List<Chromosome> childrenToAdd = new ArrayList<Chromosome>();
    /*
     * Add the result of each FutureTask to the population since it
     * represents a new child Chromosome.
     */
    for (FutureTask<List<Chromosome>> future : futureTasks) {
        try {
            /*
             * Add children after all crossover operations are completed so
             * that children are not inadvertently breeding immediately
             * after birth.
             */
            childrenToAdd.addAll(future.get());
        } catch (InterruptedException ie) {
            log.error("Caught InterruptedException while waiting for CrossoverTask ", ie);
        } catch (ExecutionException ee) {
            log.error("Caught ExecutionException while waiting for CrossoverTask ", ee);
        }
    }

    for (Chromosome child : childrenToAdd) {
        this.population.addIndividualAsIneligible(child);
    }

    return (int) pairsToCrossover;
}