Example usage for java.util.concurrent FutureTask FutureTask

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

Introduction

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

Prototype

public FutureTask(Callable<V> callable) 

Source Link

Document

Creates a FutureTask that will, upon running, execute the given Callable .

Usage

From source file:ubic.basecode.math.linalg.SingularValueDecomposition.java

/**
 * @param dm//from  ww  w .j  a  va2s . c om
 */
private void computeSVD(final DoubleMatrix2D dm) {
    /*
     * This fails to converge some times, we have to bail.
     */
    FutureTask<cern.colt.matrix.linalg.SingularValueDecomposition> svdFuture = new FutureTask<>(
            new Callable<cern.colt.matrix.linalg.SingularValueDecomposition>() {
                @Override
                public cern.colt.matrix.linalg.SingularValueDecomposition call() {
                    return new cern.colt.matrix.linalg.SingularValueDecomposition(dm);
                }
            });

    StopWatch timer = new StopWatch();
    timer.start();
    Executors.newSingleThreadExecutor().execute(svdFuture);

    while (!svdFuture.isDone() && !svdFuture.isCancelled()) {
        try {
            Thread.sleep(100);
        } catch (InterruptedException ie) {
            throw new RuntimeException("SVD cancelled");
        }
        if (timer.getTime() > MAX_COMPUTE_TIME) {
            svdFuture.cancel(true);
            throw new RuntimeException("SVD failed to converge within " + MAX_COMPUTE_TIME + "ms, bailing");
        }
    }
    timer.stop();
    try {
        this.svd = svdFuture.get();
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    } catch (ExecutionException e) {
        throw new RuntimeException(e);
    }

    assert this.svd != null;
}

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;/*from  www  . jav  a 2 s  .co  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:org.nuxeo.ecm.core.management.jtajca.CanMonitorTransactionsTest.java

@Test
public void isTotalCommitsCorrect() throws InterruptedException, ExecutionException {
    FutureTask<Boolean> commit = new FutureTask<Boolean>(new TestTotalCommits());
    executor.execute(commit);//from  w ww  .j  a va2 s  . co m
    assertThat(commit.get(), is(true));
}

From source file:pl.nask.hsn2.service.scdbg.TimedScdbgProcess.java

private static <T> T timedCall(Callable<T> c, long timeout, TimeUnit timeUnit)
        throws InterruptedException, ExecutionException, TimeoutException {
    FutureTask<T> task = new FutureTask<T>(c);
    THREAD_POOL.execute(task);//from w ww.  j  av a2s .co m
    return task.get(timeout, timeUnit);
}

From source file:dk.dbc.opensearch.datadock.DatadockPool.java

/**
 * submits a job to the threadpool for execution by a datadockThread.
 *
 * @param identifier Identifier for the job to start.
 *
 * @throws RejectedExecutionException Thrown if the threadpools jobqueue is full.
 * @throws ParserConfigurationException 
 * @throws SAXException /*from   w  w w .  j  a  v  a  2s . c om*/
 */
public void submit(IIdentifier identifier) throws RejectedExecutionException {
    if (identifier == null) {
        String error = "The submitted identifier was null, aborting task";
        log.error(error);
        throw new IllegalArgumentException(error);
    }
    log.debug(String.format("Submitting job '%s'", identifier));

    FutureTask<Boolean> future = new FutureTask<Boolean>(new DatadockThread(identifier, harvester, flowMap));

    if (future == null)/** \todo: I don't see this happening; even if DatadockThread returns null, FutureTask will still be non-null */
    {
        log.error("DatadockPool submit 'future' is null");
        throw new IllegalStateException("DatadockPool submit 'future' is null");
    }
    threadpool.submit(future);
    jobs.put(identifier, future);
}

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();// w w  w .j  a v a2s.co 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:gridool.processors.job.GridJobWorker.java

public FutureTask<R> newTask() {
    return new FutureTask<R>(this) {
        @SuppressWarnings("finally")
        public boolean cancel(boolean mayInterruptIfRunning) {
            try {
                GridJobWorker.this.cancel();
            } finally {
                return super.cancel(mayInterruptIfRunning);
            }//from w  ww. ja  va2s.  c o  m
        }
    };
}

From source file:org.b3log.latke.urlfetch.bae.BAEURLFetchService.java

/**
 * {@inheritDoc}//from   w  ww .  j a v a  2 s. c o m
 * 
 * <p>
 * <b>Note</b>: Dose <em>NOT</em> support async URL fetch at present, calls this method is equivalent to call 
 * {@link #fetch(org.b3log.latke.urlfetch.HTTPRequest)}.
 * </p>
 */
@Override
public Future<?> fetchAsync(final HTTPRequest request) {
    final FutureTask<HTTPResponse> futureTask = new FutureTask<HTTPResponse>(new Callable<HTTPResponse>() {
        @Override
        public HTTPResponse call() throws Exception {
            return fetch(request);
        }
    });

    // no pool
    futureTask.run();

    return futureTask;
}

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

/**
 * This method executes all the fitness evaluations concurrently.
 *//*from w w  w . j  a  va 2 s .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:org.springframework.batch.core.scope.AsyncJobScopeIntegrationTests.java

@Test
public void testGetSameInMultipleThreads() throws Exception {

    List<FutureTask<String>> tasks = new ArrayList<FutureTask<String>>();
    final JobExecution jobExecution = new JobExecution(11L);
    ExecutionContext executionContext = jobExecution.getExecutionContext();
    executionContext.put("foo", "foo");
    JobSynchronizationManager.register(jobExecution);
    assertEquals("foo", simple.getName());

    for (int i = 0; i < 12; i++) {
        final String value = "foo" + i;
        FutureTask<String> task = new FutureTask<String>(new Callable<String>() {
            @Override//w ww .ja  va 2  s . com
            public String call() throws Exception {
                ExecutionContext executionContext = jobExecution.getExecutionContext();
                executionContext.put("foo", value);
                JobContext context = JobSynchronizationManager.register(jobExecution);
                logger.debug("Registered: " + context.getJobExecutionContext());
                try {
                    return simple.getName();
                } finally {
                    JobSynchronizationManager.close();
                }
            }
        });
        tasks.add(task);
        taskExecutor.execute(task);
    }

    for (FutureTask<String> task : tasks) {
        assertEquals("foo", task.get());
    }

    // Don't close the outer scope until all tasks are finished. This should
    // always be the case if using an AbstractJob
    JobSynchronizationManager.close();

}