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:test.be.fedict.eid.applet.model.AuthenticationSignatureServiceBean.java

public void postSign(byte[] signatureValue, List<X509Certificate> authnCertificateChain,
        AuthenticationSignatureContext authenticationSignatureContext) {
    LOG.debug("postSign: " + (signatureValue != null));

    ProxyPrivateKey proxyPrivateKey = (ProxyPrivateKey) authenticationSignatureContext.load("key");
    proxyPrivateKey.setSignatureValue(signatureValue);

    FutureTask<String> signTask = (FutureTask<String>) authenticationSignatureContext.load("signTask");
    String signatureResult;// w  w w .j a v  a 2 s  .  co m
    try {
        signatureResult = signTask.get();
    } catch (Exception e) {
        throw new RuntimeException("sign task error: " + e.getMessage(), e);
    }

    HttpServletRequest httpServletRequest;
    try {
        httpServletRequest = (HttpServletRequest) PolicyContext
                .getContext("javax.servlet.http.HttpServletRequest");
    } catch (PolicyContextException e) {
        throw new RuntimeException("JACC error: " + e.getMessage());
    }

    HttpSession httpSession = httpServletRequest.getSession();
    httpSession.setAttribute("AuthenticationSignatureValue", signatureResult);
}

From source file:com.github.vatbub.tictactoe.view.AnimationThreadPoolExecutor.java

@SuppressWarnings("unused")
public <T> Future<T> submitWaitForUnlock(Callable<T> task) {
    Callable<T> effectiveTask = () -> {
        // PrintStreams magically don't make the wait loop hang
        PrintStream nullStream = new PrintStream(new OutputStream() {
            public void write(int b) {
                //DO NOTHING
            }// w ww. j  a v a 2  s  .  c  o  m
        });
        while (isBlocked()) {
            nullStream.println("Waiting...");
        }
        // run
        FutureTask<T> effectiveCall = new FutureTask<>(task);
        Platform.runLater(effectiveCall);
        return effectiveCall.get();
    };
    return super.schedule(effectiveTask, 0, NANOSECONDS);
}

From source file:de.appsolve.padelcampus.utils.HtmlResourceUtil.java

public void updateCss(final ServletContext context) throws Exception {
    List<Customer> customers = customerDAO.findAll();
    if (customers.isEmpty()) {
        applyCustomerCss(context, getDefaultCssAttributes(), "");
    } else {//from ww w .  jav  a2s. co m
        lessCompiler = new LessCompiler();
        lessCompiler.init();
        int availableProcessors = Runtime.getRuntime().availableProcessors();
        LOG.info(String.format("Compiling lesscss with %s cores", availableProcessors));
        ExecutorService executor = Executors.newFixedThreadPool(availableProcessors);
        List<FutureTask<Void>> taskList = new ArrayList<>();

        for (final Customer customer : customers) {
            FutureTask<Void> futureTask = new FutureTask<>(new Callable<Void>() {
                @Override
                public Void call() throws Exception {
                    try {
                        updateCss(context, customer);
                    } catch (Exception ex) {
                        LOG.error(ex, ex);
                    }
                    return null;
                }
            });
            taskList.add(futureTask);
            executor.execute(futureTask);
        }
        for (FutureTask task : taskList) {
            task.get();
        }
        executor.shutdown();
    }
}

From source file:de.uni_rostock.goodod.owl.OntologyCache.java

public OWLOntology getOntologySynchronouslyAtURI(URI theURI) throws OWLOntologyCreationException {
    OWLOntology ontology = null;/*  ww w .jav  a2  s.  c  o  m*/
    FutureTask<OWLOntology> ontologyFuture = getOntologyFutureAtURI(theURI);
    try {
        ontology = ontologyFuture.get();
    } catch (Throwable e) {
        logger.warn("Could not load ontology", e);
    }

    return ontology;
}

From source file:com.taobao.tair.comm.TairClientFactory.java

public void close() {
    for (FutureTask<TairClient> task : clients.values()) {
        if (task.isDone() || !task.cancel(true)) {
            TairClient client = null;/*  www . j  a va 2 s .c  o  m*/
            try {
                client = task.get();
            } catch (InterruptedException e) {
                LOGGER.warn(e);
            } catch (ExecutionException e) {
                LOGGER.warn(e);
            } catch (CancellationException e) {
            }
            client.close();
        }
    }
    clients.clear();
}

From source file:com.alibaba.napoli.metamorphosis.client.consumer.RecoverStorageManager.java

private Store getStore(final String name, final FutureTask<Store> task) {
    try {//from w  w w .  j  a v a 2s . c om
        return task.get();
    } catch (final Throwable t) {
        log.error("?name=" + name + "store", t);
        throw new GetRecoverStorageErrorException("?topic=" + name + "store", t);
    }

}

From source file:com.github.gregwhitaker.asyncshowdown.HelloController.java

/**
 * Asynchronously waits a random random number of milliseconds, within the specified minimum and maximum, before
 * returning a 200 HTTP response with the body containing the string "Hello World!"
 *
 * @param minSleep minimum sleep time in milliseconds
 * @param maxSleep maximum sleep time in milliseconds
 * @return A 200 HTTP response with the body containing the string "Hello World!"
 *///w  w w  .j a va 2s.  c om
@RequestMapping(value = "/hello", method = RequestMethod.GET)
public DeferredResult<ResponseEntity<String>> hello(
        @RequestParam(name = "minSleepMs", defaultValue = "500") long minSleep,
        @RequestParam(name = "maxSleepMs", defaultValue = "500") long maxSleep) {
    final DeferredResult<ResponseEntity<String>> deferredResult = new DeferredResult<>();

    final FutureTask<String> helloTask = new FutureTask(new HelloGenerator(minSleep, maxSleep));
    Observable.<String>create(sub -> {
        String message = null;
        try {
            helloTask.run();
            message = helloTask.get();
        } catch (Exception e) {
            sub.onError(e);
        }
        sub.onNext(message);
        sub.onCompleted();
    }).last().subscribeOn(Schedulers.io()).subscribe(
            message -> deferredResult.setResult(ResponseEntity.ok(message)),
            error -> deferredResult.setResult(ResponseEntity.status(500).body(error.getMessage())));

    return deferredResult;
}

From source file:com.ciphertool.sentencebuilder.etl.importers.WordListImporterImpl.java

@Override
public void importWordList() {
    // Reset the count in case this method is called again
    rowCount.set(0);/*from  w w w. java  2  s .c o  m*/

    long start = System.currentTimeMillis();

    try {
        List<Word> wordsFromFile = partOfSpeechFileParser.parseFile();

        log.info("Starting word list import...");

        List<FutureTask<Void>> futureTasks = new ArrayList<FutureTask<Void>>();
        FutureTask<Void> futureTask = null;
        List<Word> threadedWordBatch = new ArrayList<Word>();
        for (Word word : wordsFromFile) {
            threadedWordBatch.add(word);

            if (threadedWordBatch.size() >= this.concurrencyBatchSize) {
                List<Word> nextThreadedWordBatch = new ArrayList<Word>();
                int originalSize = threadedWordBatch.size();

                for (int i = 0; i < originalSize; i++) {
                    /*
                     * It's faster to remove from the end of the List
                     * because no elements need to shift
                     */
                    nextThreadedWordBatch.add(threadedWordBatch.remove(threadedWordBatch.size() - 1));
                }

                futureTask = new FutureTask<Void>(new BatchWordImportTask(nextThreadedWordBatch));
                futureTasks.add(futureTask);
                this.taskExecutor.execute(futureTask);
            }
        }

        /*
         * Start one last task if there are any leftover Words from file
         * that did not reach the batch size.
         */
        if (threadedWordBatch.size() > 0) {
            /*
             * It's safe to use the threadedWordBatch now, instead of
             * copying into a temporaryList, because this is the last thread
             * to run.
             */
            futureTask = new FutureTask<Void>(new BatchWordImportTask(threadedWordBatch));
            futureTasks.add(futureTask);
            this.taskExecutor.execute(futureTask);
        }

        for (FutureTask<Void> future : futureTasks) {
            try {
                future.get();
            } catch (InterruptedException ie) {
                log.error("Caught InterruptedException while waiting for BatchWordImportTask ", ie);
            } catch (ExecutionException ee) {
                log.error("Caught ExecutionException while waiting for BatchWordImportTask ", ee);
            }
        }
    } finally {
        log.info("Rows inserted: " + this.rowCount);
        log.info("Time elapsed: " + (System.currentTimeMillis() - start) + "ms");
    }
}

From source file:com.taobao.common.tfs.comm.TfsClientFactory.java

public TfsClient get(Long targetId, final int connectionTimeout, final PacketStreamer pstreamer)
        throws TfsException {
    final Long key = targetId;
    if (clients.containsKey(key)) {
        try {//from w  ww. j av  a  2  s .c  om
            return clients.get(key).get();
        } catch (Exception e) {
            removeClient(key);
            throw new TfsException("get tfs connection error,targetAddress is " + targetId, e);
        }
    } else {
        FutureTask<TfsClient> task = new FutureTask<TfsClient>(new Callable<TfsClient>() {
            public TfsClient call() throws Exception {
                return createClient(key, connectionTimeout, pstreamer);
            }
        });
        FutureTask<TfsClient> existTask = clients.putIfAbsent(key, task);
        if (existTask == null) {
            existTask = task;
            task.run();
        }
        try {
            return existTask.get();
        } catch (Exception e) {
            removeClient(key);
            throw new TfsException("get tfs connection error,targetAddress is " + targetId, e);
        }
    }
}

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 ww w  .  j  a  v a2 s  .  c  o  m
    assertThat(commit.get(), is(true));
}