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:net.bither.ui.base.AddressDetailHeader.java

public void showAddress(final Address address, int addressPosition) {
    this.addressPosition = addressPosition;
    if (address.getAddress() == null) {
        return;//  w  w w.j a  va  2s.  c  o  m
    }
    tvAddress.setText(WalletUtils.formatHash(address.getAddress(), 4, 12));
    if (this.address != address) {
        Qr.QrCodeTheme theme = AppSharedPreference.getInstance().getFancyQrCodeTheme();
        ivQr.setContent(address.getAddress(), theme.getFgColor(), theme.getBgColor());
    }

    llMore.setVisibility(View.VISIBLE);
    if (address.txCount() == 0) {
        tvNoTransactions.setVisibility(View.VISIBLE);
    } else {
        tvNoTransactions.setVisibility(View.GONE);
    }
    btnBalance.setAmount(address.getBalance());
    if (address.hasPrivKey()) {
        btnSend.setCompoundDrawables(null, null, null, null);
    } else {
        Drawable d = getContext().getResources().getDrawable(R.drawable.unsigned_transaction_button_icon);
        int size = UIUtil.dip2pix(20);
        int topOffset = UIUtil.dip2pix(0.5f);
        d.setBounds(0, topOffset, size, size + topOffset);
        btnSend.setCompoundDrawables(null, null, d, null);
    }
    //        } else {
    //            llMore.setVisibility(View.GONE);
    //        }
    llMonitorFailed.setVisibility(View.GONE);
    //        } else {
    //            llMore.setVisibility(View.GONE);
    //            tvNoTransactions.setVisibility(View.GONE);
    //            llMonitorFailed.setVisibility(View.VISIBLE);
    //        }
    this.address = address;
    if (balanceDetailFuture != null) {
        balanceDetailFuture.cancel(true);
    }
    balanceDetailFuture = new FutureTask<DialogBalanceDetail.Info>(getBalanceInfo);
    new Thread(balanceDetailFuture).start();
}

From source file:org.nuxeo.ecm.core.management.jtajca.CanMonitorTransactionsTest.java

@Test
@LogCaptureFeature.FilterWith(value = CanMonitorTransactionsTest.LogRollbackTraceFilter.class)
public void logContainsRollbackTrace()
        throws InterruptedException, ExecutionException, NoLogCaptureFilterException {
    FutureTask<Boolean> task = new FutureTask<Boolean>(new TestLogRollbackTrace());
    executor.execute(task);//from   ww w  . j  a  va2  s .  c  o m
    assertThat(task.get(), is(true));
    logCaptureResults.assertHasEvent();
}

From source file:org.apache.qpid.disttest.client.MessageProvider.java

protected String getMessagePayload(final CreateProducerCommand command) {
    FutureTask<String> createTextFuture = new FutureTask<String>(new Callable<String>() {
        @Override/*ww  w.j  av a 2  s. c  o  m*/
        public String call() throws Exception {
            return StringUtils.repeat("a", command.getMessageSize());
        }
    });

    Future<String> future = _payloads.putIfAbsent(command.getMessageSize(), createTextFuture);
    if (future == null) {
        createTextFuture.run();
        future = createTextFuture;
    }
    String payload = null;
    try {
        payload = future.get();
    } catch (Exception e) {
        throw new DistributedTestException("Unable to create message payload :" + e.getMessage(), e);
    }
    return payload;
}

From source file:org.apache.nutch.parse.ParseUtil.java

private ParseResult runParser(Parser p, Content content) {
    ParseCallable pc = new ParseCallable(p, content);
    FutureTask<ParseResult> task = new FutureTask<ParseResult>(pc);
    ParseResult res = null;/*from   w ww. j a v  a2 s. c o  m*/
    Thread t = new Thread(task);
    t.start();
    try {
        res = task.get(MAX_PARSE_TIME, TimeUnit.SECONDS);
    } catch (TimeoutException e) {
        LOG.warn("TIMEOUT parsing " + content.getUrl() + " with " + p);
    } catch (Exception e) {
        task.cancel(true);
        res = null;
        t.interrupt();
    } finally {
        t = null;
        pc = null;
    }
    return res;
}

From source file:ubic.gemma.core.loader.util.fetcher.FtpArchiveFetcher.java

protected void unPack(final File toUnpack) {
    FutureTask<Boolean> future = new FutureTask<>(new Callable<Boolean>() {
        @Override//  w w w . j  av a  2 s.  c o m
        @SuppressWarnings("synthetic-access")
        public Boolean call() {
            File extractedFile = new File(FileTools.chompExtension(toUnpack.getAbsolutePath()));
            /*
             * Decide if an existing file is plausibly usable. Err on the side of caution.
             */
            if (allowUseExisting && extractedFile.canRead() && extractedFile.length() >= toUnpack.length()
                    && !FileUtils.isFileNewer(toUnpack, extractedFile)) {
                AbstractFetcher.log.warn("Expanded file exists, skipping re-expansion: " + extractedFile);
                return Boolean.TRUE;
            }

            if (expander != null) {
                expander.setSrc(toUnpack);
                expander.setDest(toUnpack.getParentFile());
                expander.perform();
            } else if (toUnpack.getAbsolutePath().toLowerCase().endsWith("zip")) {
                try {
                    FileTools.unZipFiles(toUnpack.getAbsolutePath());
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }

            } else { // gzip.
                try {
                    FileTools.unGzipFile(toUnpack.getAbsolutePath());
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }

            return Boolean.TRUE;
        }

    });
    ExecutorService executor = Executors.newSingleThreadExecutor();

    executor.execute(future);
    executor.shutdown();

    StopWatch s = new StopWatch();
    s.start();
    while (!future.isDone() && !future.isCancelled()) {
        try {
            Thread.sleep(AbstractFetcher.INFO_UPDATE_INTERVAL);
        } catch (InterruptedException ie) {
            future.cancel(true);
            return;
        }
        AbstractFetcher.log
                .info("Unpacking archive ... " + Math.floor(s.getTime() / 1000.0) + " seconds elapsed");
    }
}

From source file:org.ms123.common.camel.components.BaseCamelBehavior.java

public void execute(ActivityExecution execution) throws Exception {
    m_js.prettyPrint(true);// w  w  w . j a v a  2 s  .com
    m_execution = execution;
    debug("BaseCamelBehavior.execution:" + isASync(execution));

    Map mapBody = getVarMapping(execution, variablesmapping, DESTINATION_BODY);
    debug("MappingBody:" + m_js.deepSerialize(mapBody));
    Map mapProp = getVarMapping(execution, variablesmapping, DESTINATION_PROP);
    debug("MappingProp:" + m_js.deepSerialize(mapProp));
    Map mapHeader = getVarMapping(execution, variablesmapping, DESTINATION_HEADER);
    debug("MappingHeader:" + m_js.deepSerialize(mapHeader));
    m_mapRouting = getVarMapping(execution, variablesmapping, DESTINATION_ROUTING);
    debug("MappingRouting:" + m_js.deepSerialize(m_mapRouting));

    setTenantAndName(execution);
    m_camelContext = createCamelContext(m_tenant);
    createRouteBuilderClazz();
    addRoute(m_camelContext, execution);
    m_camelContext.start();
    final ActivitiEndpoint endpoint = createEndpoint(execution);
    final Exchange exchange = createExchange(execution, endpoint);
    exchange.setProperty("activitikey", m_camelActivitiKey);
    copyVariablesToProperties(mapProp, exchange);
    copyVariablesToHeader(mapHeader, exchange);
    copyVariablesToBodyAsMap(mapBody, exchange);
    final CamelService camelService = (CamelService) m_camelContext.getRegistry()
            .lookupByName(CamelService.class.getName());
    if (isASync(execution)) {
        FutureTask<Void> future = new FutureTask<Void>(new Callable<Void>() {

            public Void call() {
                try {
                    endpoint.process(exchange);
                } catch (Exception e) {
                    throw new RuntimeException("Unable to process camel endpoint asynchronously.");
                } finally {
                    Exception camelException = exchange.getException();
                    info("camelException:" + camelException);
                    printHistory(exchange);
                    camelService.saveHistory(exchange);
                    try {
                        info("Context stop");
                        m_camelContext.stop();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                return null;
            }
        });
        ExecutorService executor = Executors.newSingleThreadExecutor();
        executor.submit(future);
        handleCamelException(exchange);
    } else {
        try {
            endpoint.process(exchange);
            handleCamelException(exchange);
            debug(ExchangeUtils.prepareVariables(exchange, endpoint) + "");
            String rs = null;
            if (resultvar != null) {
                rs = resultvar.getValue(execution).toString();
            }
            if (isEmpty(rs)) {
                execution.setVariables(ExchangeUtils.prepareVariables(exchange, endpoint));
            } else {
                execution.setVariable(rs, ExchangeUtils.prepareVariables(exchange, endpoint));
            }
        } finally {
            printHistory(exchange);
            camelService.saveHistory(exchange);
            m_camelContext.stop();
        }
    }
    performDefaultOutgoingBehavior(execution);
}

From source file:de.elomagic.mag.AbstractTest.java

protected Future<byte[]> createFileExistsFuture(Path file) {

    ExecutorService executor = Executors.newFixedThreadPool(2);

    FutureTask<byte[]> futureTask = new FutureTask<>(() -> {
        byte[] result = null;
        do {//  w ww.ja  v  a  2s . co  m
            if (Files.exists(file)) {
                InputStream in = Files.newInputStream(file, StandardOpenOption.READ);
                result = IOUtils.readFully(in, in.available());
            }

            Thread.sleep(100);
        } while (result == null);

        return result;
    });

    executor.execute(futureTask);

    return futureTask;
}

From source file:com.hortonworks.registries.storage.filestorage.DbFileStorageTest.java

@Test(expected = StorageException.class)
public void testConcurrentUpload() throws Throwable {
    try {//  w w w .  j  a va 2s  .c o m
        transactionManager.beginTransaction(TransactionIsolation.SERIALIZABLE);
        String input = IOUtils.toString(this.getClass().getClassLoader().getResourceAsStream(FILE_NAME),
                "UTF-8");
        String updated = input + " new text";
        dbFileStorage.upload(IOUtils.toInputStream(input, "UTF-8"), FILE_NAME);
        InputStream slowStream = new InputStream() {
            byte[] bytes = updated.getBytes("UTF-8");
            int i = 0;

            @Override
            public int read() throws IOException {
                try {
                    Thread.sleep(10);
                } catch (InterruptedException ex) {
                }
                return (i < bytes.length) ? (bytes[i++] & 0xff) : -1;
            }
        };
        FutureTask<String> ft1 = new FutureTask<>(() -> {
            try {
                transactionManager.beginTransaction(TransactionIsolation.SERIALIZABLE);
                String name = dbFileStorage.upload(slowStream, FILE_NAME);
                transactionManager.commitTransaction();
                return name;
            } catch (Exception e) {
                transactionManager.rollbackTransaction();
                throw e;
            }
        });
        FutureTask<String> ft2 = new FutureTask<>(() -> {
            try {
                transactionManager.beginTransaction(TransactionIsolation.SERIALIZABLE);
                String name = dbFileStorage.upload(IOUtils.toInputStream(updated, "UTF-8"), FILE_NAME);
                transactionManager.commitTransaction();
                return name;
            } catch (Exception e) {
                transactionManager.rollbackTransaction();
                throw e;
            }
        });
        Thread t1 = new Thread(ft1);
        Thread t2 = new Thread(ft2);
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        try {
            ft1.get();
        } catch (ExecutionException ex) {
            throw ex.getCause();
        }
        transactionManager.commitTransaction();
    } catch (Exception e) {
        transactionManager.rollbackTransaction();
        throw e;
    }
}

From source file:uk.ac.kcl.iop.brc.core.pipeline.common.service.DocumentConversionService.java

private File makeTiffFromPDF(DNCWorkCoordinate coordinate, File input) throws IOException, TikaException {
    File output = File.createTempFile(coordinate.getFileName(), ".tiff");
    String[] cmd = { getImageMagickProg(), "-density", "300", input.getPath(), "-depth", "8", "-quality", "1",
            output.getPath() };//  www  .  j  a v a2 s  .c o  m
    Process process = new ProcessBuilder(cmd).start();
    IOUtils.closeQuietly(process.getOutputStream());
    InputStream processInputStream = process.getInputStream();
    logStream(processInputStream);
    FutureTask<Integer> waitTask = new FutureTask<>(process::waitFor);
    Thread waitThread = new Thread(waitTask);
    waitThread.start();
    try {
        waitTask.get(240, TimeUnit.SECONDS);
        return output;
    } catch (Exception e) {
        logger.error(e.getMessage());
        waitThread.interrupt();
        process.destroy();
        Thread.currentThread().interrupt();
        waitTask.cancel(true);
    } finally {
        IOUtils.closeQuietly(processInputStream);
        process.destroy();
        waitThread.interrupt();
        waitTask.cancel(true);
    }
    return null;
}

From source file:com.rk.grid.cluster.master.Broker.java

private final FutureTask<V> getFutureRemoveTask(final String key) {
    Callable<V> task = new Callable<V>() {
        @Override/*from   w  ww. ja v a2 s. co m*/
        public V call() throws Exception {
            IRemoteResult<V> result = blockingMap.removeWhenPresent(key);
            return result.getResult();
        }
    };
    return new FutureTask<V>(task);
}