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:com.taobao.tair.comm.TairClientFactory.java

public TairClient get(final String targetUrl, final int connectionTimeout, final PacketStreamer pstreamer)
        throws TairClientException {
    String key = targetUrl;//from  w ww .j a  va  2 s .com
    FutureTask<TairClient> existTask = null;
    existTask = clients.get(key);

    if (existTask == null) {
        FutureTask<TairClient> task = new FutureTask<TairClient>(new Callable<TairClient>() {
            public TairClient call() throws Exception {
                return createClient(targetUrl, connectionTimeout, pstreamer);
            }
        });
        existTask = clients.putIfAbsent(key, task);
        if (existTask == null) {
            existTask = task;
            task.run();
        }
    }

    try {
        return existTask.get();
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    } catch (CancellationException e) {
        // cancel exception may be lost connection fd, but we never called task.cancel();
        clients.remove(key);
        throw e;
    } catch (ExecutionException e) {
        // create socket failed, so need not close
        clients.remove(key);
        throw new TairClientException("create socket exception, target address is " + targetUrl, e);
    }
}

From source file:test.be.fedict.eid.applet.model.AuthenticationSignatureServiceBean.java

public PreSignResult preSign(List<X509Certificate> authnCertificateChain,
        AuthenticationSignatureContext authenticationSignatureContext) {
    LOG.debug("preSign");
    LOG.debug("authn cert chain size: " + authnCertificateChain.size());

    KeyStore proxyKeyStore;/*  w  ww. j ava  2s  .  c o m*/
    final ProxyPrivateKey proxyPrivateKey;
    try {
        proxyKeyStore = KeyStore.getInstance("ProxyBeID");
        proxyKeyStore.load(null);
        proxyPrivateKey = (ProxyPrivateKey) proxyKeyStore.getKey("Signature", null);
    } catch (Exception e) {
        throw new RuntimeException("error loading ProxyBeID keystore");
    }

    FutureTask<String> signTask = new FutureTask<String>(new Callable<String>() {
        public String call() throws Exception {
            final Signature signature = Signature.getInstance("SHA256withRSA");
            signature.initSign(proxyPrivateKey);

            final byte[] toBeSigned = "hello world".getBytes();
            signature.update(toBeSigned);
            final byte[] signatureValue = signature.sign();
            LOG.debug("received signature value");
            return "signature result";
        }

    });
    final ExecutorService executor = Executors.newFixedThreadPool(1);
    executor.execute(signTask);

    authenticationSignatureContext.store("key", proxyPrivateKey);
    authenticationSignatureContext.store("signTask", signTask);

    byte[] digestValue;
    try {
        digestValue = proxyPrivateKey.getDigestInfo().getDigestValue();
    } catch (InterruptedException e) {
        throw new RuntimeException("signature error: " + e.getMessage(), e);
    }
    DigestInfo digestInfo = new DigestInfo(digestValue, "SHA-256", "WS-Security message");
    PreSignResult preSignResult = new PreSignResult(digestInfo, true);
    return preSignResult;
}

From source file:com.loopj.android.http.sample.AsyncBackgroundThreadSample.java

@Override
public ResponseHandlerInterface getResponseHandler() {

    FutureTask<ResponseHandlerInterface> future = new FutureTask<>(new Callable<ResponseHandlerInterface>() {

        @Override/*from  w ww  . ja v  a  2 s.c  o  m*/
        public ResponseHandlerInterface call() throws Exception {
            Log.d(LOG_TAG, "Creating AsyncHttpResponseHandler on background thread");
            return new AsyncHttpResponseHandler(Looper.getMainLooper()) {

                @Override
                public void onStart() {
                    clearOutputs();
                }

                @Override
                public void onSuccess(int statusCode, Header[] headers, byte[] response) {
                    Log.d(LOG_TAG, String.format("onSuccess executing on main thread : %B",
                            Looper.myLooper() == Looper.getMainLooper()));
                    debugHeaders(LOG_TAG, headers);
                    debugStatusCode(LOG_TAG, statusCode);
                    debugResponse(LOG_TAG, new String(response));
                }

                @Override
                public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {
                    Log.d(LOG_TAG, String.format("onFailure executing on main thread : %B",
                            Looper.myLooper() == Looper.getMainLooper()));
                    debugHeaders(LOG_TAG, headers);
                    debugStatusCode(LOG_TAG, statusCode);
                    debugThrowable(LOG_TAG, e);
                    if (errorResponse != null) {
                        debugResponse(LOG_TAG, new String(errorResponse));
                    }
                }

                @Override
                public void onRetry(int retryNo) {
                    Toast.makeText(AsyncBackgroundThreadSample.this,
                            String.format("Request is retried, retry no. %d", retryNo), Toast.LENGTH_SHORT)
                            .show();
                }
            };
        }
    });

    executor.execute(future);

    ResponseHandlerInterface responseHandler = null;
    try {
        responseHandler = future.get();
        Log.d(LOG_TAG, "Background thread for AsyncHttpResponseHandler has finished");
    } catch (Exception e) {
        e.printStackTrace();
    }

    return responseHandler;
}

From source file:com.skymobi.monitor.service.TaskService.java

public FutureTask<CommandResult> runScript(final String script, final Project project) {
    FutureTask<CommandResult> _fuFutureTask = new FutureTask(new Callable() {

        @Override//from w ww.j a  va2 s .c  om
        public CommandResult call() throws Exception {

            logger.debug("run mongo script = {}", script);
            CommandResult result = project.fetchMongoTemplate().getDb().doEval(script,
                    new BasicDBObject().append("nolock", true));
            logger.debug("mongo task response {}", result);
            return result;
        }
    });
    executor.submit(_fuFutureTask);
    return _fuFutureTask;
}

From source file:eu.stratosphere.pact.runtime.cache.FileCache.java

/**
 * If the file doesn't exists locally, it will copy the file to the temp directory.
 *//* ww  w. j av a 2 s. c o  m*/
public FutureTask<Path> createTmpFile(String name, String filePath, JobID jobID) {

    synchronized (count) {
        Pair<JobID, String> key = new ImmutablePair(jobID, name);
        if (count.containsKey(key)) {
            count.put(key, count.get(key) + 1);
        } else {
            count.put(key, 1);
        }
    }
    CopyProcess cp = new CopyProcess(name, filePath, jobID);
    FutureTask<Path> copyTask = new FutureTask<Path>(cp);
    executorService.submit(copyTask);
    return copyTask;
}

From source file:com.linuxbox.enkive.message.search.AbstractMessageSearchService.java

@Override
@Async//from  w  w w .  j a v a  2  s  . c om
public Future<SearchResult> searchAsync(final Map<String, String> fields) throws MessageSearchException {
    FutureTask<SearchResult> searchFuture = new FutureTask<SearchResult>(new Callable<SearchResult>() {
        public SearchResult call() {
            SearchResult result = null;
            try {
                result = search(fields);
            } catch (MessageSearchException e) {
                if (LOGGER.isWarnEnabled())
                    LOGGER.warn("Error Searching for message", e);
            }
            return result;
        }
    });
    searchFuture.run();
    return searchFuture;
}

From source file:ubic.gemma.loader.util.fetcher.FtpFetcher.java

/**
 * @param outputFileName//from w  ww. j a va2s  .com
 * @param seekFile
 * @return
 */
protected FutureTask<Boolean> defineTask(final String outputFileName, final String seekFile) {
    FutureTask<Boolean> future = new FutureTask<Boolean>(new Callable<Boolean>() {
        @Override
        public Boolean call() throws FileNotFoundException, IOException {
            File existing = new File(outputFileName);
            if (existing.exists() && avoidDownload) {
                log.info("A local file exists, skipping download.");
                ftpClient.disconnect();
                return Boolean.TRUE;
            } else if (existing.exists() && allowUseExisting) {
                log.info("Checking validity of existing local file: " + outputFileName);
            } else {
                log.info("Fetching " + seekFile + " to " + outputFileName);
            }
            boolean status = NetUtils.ftpDownloadFile(ftpClient, seekFile, outputFileName, force);
            ftpClient.disconnect();
            return new Boolean(status);
        }
    });
    return future;
}

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);/*ww  w . j  a  v  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.sentencebuilder.etl.importers.WordListImporterImpl.java

@Override
public void importWordList() {
    // Reset the count in case this method is called again
    rowCount.set(0);/* ww w .ja v a 2 s  .  c  om*/

    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.appleframework.monitor.service.TaskService.java

@SuppressWarnings("rawtypes")
public FutureTask<CommandResult> runScript(final String script, final Project project) {
    FutureTask<CommandResult> _fuFutureTask = new FutureTask<CommandResult>(new Callable() {
        @Override//www  .  ja va2 s.c om
        public CommandResult call() throws Exception {
            logger.debug("run mongo script = {}", script);
            CommandResult result = project.fetchMongoTemplate().getDb().doEval(script,
                    new BasicDBObject().append("nolock", true));
            logger.debug("mongo task response {}", result);
            return result;
        }
    });
    executor.submit(_fuFutureTask);
    return _fuFutureTask;
}