Example usage for com.google.common.util.concurrent MoreExecutors listeningDecorator

List of usage examples for com.google.common.util.concurrent MoreExecutors listeningDecorator

Introduction

In this page you can find the example usage for com.google.common.util.concurrent MoreExecutors listeningDecorator.

Prototype

@GwtIncompatible("TODO")
public static ListeningScheduledExecutorService listeningDecorator(ScheduledExecutorService delegate) 

Source Link

Document

Creates a ScheduledExecutorService whose submit and invokeAll methods submit ListenableFutureTask instances to the given delegate executor.

Usage

From source file:com.google.gerrit.pgm.RebuildNoteDb.java

private ListeningExecutorService newExecutor() {
    if (threads > 0) {
        return MoreExecutors.listeningDecorator(workQueue.createQueue(threads, "RebuildChange"));
    }// w w w  .  j a  v a2 s  .com
    return MoreExecutors.newDirectExecutorService();
}

From source file:org.apache.crunch.hadoop.mapreduce.lib.jobcontrol.CrunchJobControl.java

synchronized private void executeReadySeqDoFns() {
    Set<Target> unfinished = getUnfinishedTargets();
    Set<PipelineCallable<?>> oldPipelineCallables = activePipelineCallables;
    this.activePipelineCallables = Sets.newHashSet();
    List<Callable<PipelineCallable.Status>> callablesToRun = Lists.newArrayList();
    for (final PipelineCallable<?> pipelineCallable : oldPipelineCallables) {
        if (Sets.intersection(allPipelineCallables.get(pipelineCallable), unfinished).isEmpty()) {
            if (pipelineCallable.runSingleThreaded()) {
                try {
                    if (pipelineCallable.call() != PipelineCallable.Status.SUCCESS) {
                        failedCallables.add(pipelineCallable);
                    }//from w  w  w.  j a  v a 2 s . c  om
                } catch (Throwable t) {
                    pipelineCallable.setMessage(t.getLocalizedMessage());
                    failedCallables.add(pipelineCallable);
                }
            } else {
                callablesToRun.add(pipelineCallable);
            }
        } else {
            // Still need to run this one
            activePipelineCallables.add(pipelineCallable);
        }
    }

    ListeningExecutorService es = MoreExecutors.listeningDecorator(Executors.newCachedThreadPool());
    try {
        List<Future<PipelineCallable.Status>> res = es.invokeAll(callablesToRun);
        for (int i = 0; i < res.size(); i++) {
            if (res.get(i).get() != PipelineCallable.Status.SUCCESS) {
                failedCallables.add((PipelineCallable) callablesToRun.get(i));
            }
        }
    } catch (Throwable t) {
        t.printStackTrace();
        failedCallables.addAll((List) callablesToRun);
    } finally {
        es.shutdownNow();
    }
}

From source file:io.druid.server.coordinator.CostBalancerStrategy.java

/**
 * For assignment, we want to move to the lowest cost server that isn't already serving the segment.
 *
 * @param proposalSegment A DataSegment that we are proposing to move.
 * @param serverHolders   An iterable of ServerHolders for a particular tier.
 *
 * @return A ServerHolder with the new home for a segment.
 *//*from   w  ww .j  a va2 s .  co m*/

protected Pair<Double, ServerHolder> chooseBestServer(final DataSegment proposalSegment,
        final Iterable<ServerHolder> serverHolders, final boolean includeCurrentServer) {
    Pair<Double, ServerHolder> bestServer = Pair.of(Double.POSITIVE_INFINITY, null);

    ListeningExecutorService service = MoreExecutors
            .listeningDecorator(Executors.newFixedThreadPool(threadCount));
    List<ListenableFuture<Pair<Double, ServerHolder>>> futures = Lists.newArrayList();

    for (final ServerHolder server : serverHolders) {
        futures.add(service.submit(new Callable<Pair<Double, ServerHolder>>() {
            @Override
            public Pair<Double, ServerHolder> call() throws Exception {
                return Pair.of(computeCost(proposalSegment, server, includeCurrentServer), server);
            }
        }));
    }

    final ListenableFuture<List<Pair<Double, ServerHolder>>> resultsFuture = Futures.allAsList(futures);

    try {
        for (Pair<Double, ServerHolder> server : resultsFuture.get()) {
            if (server.lhs < bestServer.lhs) {
                bestServer = server;
            }
        }
    } catch (Exception e) {
        log.makeAlert(e, "Cost Balancer Multithread strategy wasn't able to complete cost computation.").emit();
    }
    service.shutdown();
    return bestServer;
}

From source file:org.multibit.viewsystem.swing.action.SendBitcoinConfirmAction.java

/**
 * Complete the transaction to work out the fee) and then show the send bitcoin confirm dialog.
 *//*ww w . j a va 2s  .com*/
@Override
public void actionPerformed(ActionEvent e) {
    if (abort()) {
        return;
    }

    //        SendBitcoinConfirmDialog sendBitcoinConfirmDialog = null;
    ValidationErrorDialog validationErrorDialog = null;

    try {
        String sendAddress = dataProvider.getAddress();
        String sendAmount = dataProvider.getAmount();
        String sendMessage = null;
        boolean canSendMessage = false;

        /*CoinSpark START */
        CoinSparkPaymentRef paymentRef = null;

        /*
         If the address is a coinspark address, retrieve the bitcoin address and let the validator check it.
         The SendRequest object will use the bitcoin address, while the confirmation dialog will use
         whatever is displayed in the address text field i.e. coinspark address, if there is one.
         For reference, you can see what is in the textfield, which has been saved in prefs:
         String address = this.bitcoinController.getModel().getActiveWalletPreference(BitcoinModel.SEND_ADDRESS
         */
        if (sendAddress.startsWith("s")) {
            CoinSparkAddress csa = CSMiscUtils.decodeCoinSparkAddress(sendAddress);
            String btcAddress = CSMiscUtils.getBitcoinAddressStringFromCoinSparkAddress(csa);
            if (btcAddress != null) {
                sendAddress = btcAddress; // the validator will check the btcAddress like normal.
            }

            // Does a payment ref exist?
            int flags = csa.getAddressFlags();
            if ((flags & CoinSparkAddress.COINSPARK_ADDRESS_FLAG_PAYMENT_REFS) > 0) {
                paymentRef = csa.getPaymentRef();
            }

            // Messages - can send message and BTC to CoinSpark address, without any assets.
            sendMessage = ((AssetFormDataProvider) dataProvider).getMessage();
            canSendMessage = (flags & CoinSparkAddress.COINSPARK_ADDRESS_FLAG_TEXT_MESSAGES) > 0;
        }
        /*CoinSpark END */

        Validator validator = new Validator(super.bitcoinController);
        if (validator.validate(sendAddress, sendAmount)) {
            // The address and amount are valid.

            // Create a SendRequest.
            Address sendAddressObject;

            sendAddressObject = new Address(bitcoinController.getModel().getNetworkParameters(), sendAddress);
            final SendRequest sendRequest = SendRequest.to(sendAddressObject, Utils.toNanoCoins(sendAmount));
            //                SendRequest sendRequest = SendRequest.to(sendAddressObject, Utils.toNanoCoins(sendAmount), 6, new BigInteger("10000"),1);
            sendRequest.ensureMinRequiredFee = true;
            sendRequest.fee = BigInteger.ZERO;
            sendRequest.feePerKb = BitcoinModel.SEND_FEE_PER_KB_DEFAULT;

            // Note - Request is populated with the AES key in the SendBitcoinNowAction after the user has entered it on the SendBitcoinConfirm form.

            // Send with payment ref - if it exists and is not 0 which SparkBit treats semantically as null
            if (paymentRef != null && paymentRef.getRef() != 0) {
                sendRequest.setPaymentRef(paymentRef);
            }

            // Send a message if the address will take it and message is not empty
            boolean willSendMessage = false;
            if (canSendMessage) {
                boolean isEmptyMessage = false;
                if (sendMessage == null || sendMessage.isEmpty() || sendMessage.trim().length() == 0) {
                    isEmptyMessage = true;
                }
                if (!isEmptyMessage) {
                    willSendMessage = true;
                    CoinSparkMessagePart[] parts = {
                            CSMiscUtils.createPlainTextCoinSparkMessagePart(sendMessage) };
                    String[] serverURLs = CSMiscUtils.getMessageDeliveryServersArray(bitcoinController);
                    sendRequest.setMessage(parts, serverURLs);

                    log.debug(">>>> Messaging servers = " + ArrayUtils.toString(serverURLs));
                    log.debug(">>>> parts[0] = " + parts[0]);
                    log.debug(">>>> parts[0].fileName = " + parts[0].fileName);
                    log.debug(">>>> parts[0].mimeType = " + parts[0].mimeType);
                    log.debug(">>>> parts[0].content = " + new String(parts[0].content, "UTF-8"));
                    //String message = "Hello, the time is now..." + DateTime.now().toString();
                    //      parts[2].fileName = imagePath;
                    //      parts[2].mimeType = "image/png";
                    //      byte[] imageBytes = Files.readAllBytes(Paths.get(imagePath));
                    //      parts[2].content = imageBytes;

                }
            }

            //
            // When sending a message, show a modal dialog.
            // CompleteTX now occurs in background thread so UI does not block
            // when "Send" is clicked with widget updates frozen.
            //

            // Show dialog with indeterminate progress bar
            final JDialog dialog = CSMiscUtils.createModalMessageDialogWithIndeterminateProgress(mainFrame,
                    "SparkBit", "Contacting message delivery servers...");
            // Dialog is made visible after futures have been set up

            ListeningExecutorService service = MoreExecutors
                    .listeningDecorator(Executors.newSingleThreadExecutor()); //newFixedThreadPool(10));
            ListenableFuture<Boolean> future = service.submit(new Callable<Boolean>() {
                public Boolean call() throws Exception {
                    try {
                        // Complete it (which works out the fee) but do not sign it yet.
                        log.debug("Just about to complete the tx (and calculate the fee)...");
                        bitcoinController.getModel().getActiveWallet().completeTx(sendRequest, false);
                        log.debug("The fee after completing the transaction was " + sendRequest.fee);

                    } catch (Exception e) {
                        throw e;
                    }
                    return true;
                }
            });

            Futures.addCallback(future, new FutureCallback<Boolean>() {
                public void onSuccess(Boolean b) {

                    // There is enough money.
                    SwingUtilities.invokeLater(new Runnable() {
                        @Override
                        public void run() {
                            dialog.dispose();

                            SendBitcoinConfirmDialog mySendBitcoinConfirmDialog = new SendBitcoinConfirmDialog(
                                    bitcoinController, mainFrame, sendRequest);
                            mySendBitcoinConfirmDialog.setVisible(true);
                        }
                    });

                }

                public void onFailure(Throwable thrown) {
                    final String failureReason = thrown.getMessage();
                    final boolean isCSException = thrown instanceof org.coinspark.core.CSExceptions.CannotEncode;
                    final boolean isInsufficientMoney = thrown instanceof com.google.bitcoin.core.InsufficientMoneyException;
                    // There is not enough money.
                    // TODO setup validation parameters accordingly so that it displays ok.
                    SwingUtilities.invokeLater(new Runnable() {
                        @Override
                        public void run() {
                            dialog.dispose();

                            if (isCSException) {
                                JOptionPane
                                        .showMessageDialog(mainFrame,
                                                "SparkBit is unable to proceed with this transaction:\n\n"
                                                        + failureReason,
                                                "SparkBit Error", JOptionPane.ERROR_MESSAGE);
                            } else if (isInsufficientMoney) {
                                // Try to show a human friendly message, need to pass the missing satoshis from failure reason.
                                try {
                                    String numberOnly = failureReason.replaceAll("[^0-9]", "");
                                    BigInteger needed = new BigInteger(numberOnly);
                                    JOptionPane.showMessageDialog(mainFrame,
                                            "SparkBit is unable to proceed with this transaction.\n\nInsufficient money in wallet, require "
                                                    + Utils.bitcoinValueToFriendlyString(needed) + " BTC more.",
                                            "SparkBit Error", JOptionPane.ERROR_MESSAGE);
                                } catch (NumberFormatException e) {
                                    ValidationErrorDialog myValidationErrorDialog = new ValidationErrorDialog(
                                            bitcoinController, mainFrame, sendRequest, true);
                                    myValidationErrorDialog.setVisible(true);
                                }
                            } else {
                                ValidationErrorDialog myValidationErrorDialog = new ValidationErrorDialog(
                                        bitcoinController, mainFrame, sendRequest, true);
                                myValidationErrorDialog.setVisible(true);
                            }
                        }
                    });
                }
            });

            // Show message server dialog only if we are going to send
            if (willSendMessage) {
                dialog.setVisible(true);
            }

            /*      
                            // Complete it (which works out the fee) but do not sign it yet.
                            log.debug("Just about to complete the tx (and calculate the fee)...");
                            boolean completedOk;
                            try {
            bitcoinController.getModel().getActiveWallet().completeTx(sendRequest, false);
                              completedOk = true;
                              log.debug("The fee after completing the transaction was " + sendRequest.fee);
                            } catch (InsufficientMoneyException ime) {
                              completedOk = false;
                            }
                            if (completedOk) {
            // There is enough money.
                    
            sendBitcoinConfirmDialog = new SendBitcoinConfirmDialog(super.bitcoinController, mainFrame, sendRequest);
            sendBitcoinConfirmDialog.setVisible(true);
                            } else {
            // There is not enough money.
            // TODO setup validation parameters accordingly so that it displays ok.
            validationErrorDialog = new ValidationErrorDialog(super.bitcoinController, mainFrame, sendRequest, true);
            validationErrorDialog.setVisible(true);
                            }
               */

        } else {
            validationErrorDialog = new ValidationErrorDialog(super.bitcoinController, mainFrame, null, false);
            validationErrorDialog.setVisible(true);
        }
    } catch (WrongNetworkException e1) {
        logMessage(e1);
    } catch (AddressFormatException e1) {
        logMessage(e1);
    } catch (KeyCrypterException e1) {
        logMessage(e1);
    } catch (Exception e1) {
        logMessage(e1);
    }
}

From source file:com.facebook.buck.maven.Resolver.java

private ImmutableSetMultimap<Path, Prebuilt> downloadArtifacts(final MutableDirectedGraph<Artifact> graph)
        throws ExecutionException, InterruptedException {
    ListeningExecutorService exec = MoreExecutors
            .listeningDecorator(Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors(),
                    new MostExecutors.NamedThreadFactory("artifact download")));

    @SuppressWarnings("unchecked")
    List<ListenableFuture<Map.Entry<Path, Prebuilt>>> results = (List<ListenableFuture<Map.Entry<Path, Prebuilt>>>) (List<?>) exec
            .invokeAll(graph.getNodes().stream().map(
                    artifact -> (Callable<Map.Entry<Path, Prebuilt>>) () -> downloadArtifact(artifact, graph))
                    .collect(MoreCollectors.toImmutableList()));

    try {//w w  w .ja v a  2 s . c o m
        return ImmutableSetMultimap.<Path, Prebuilt>builder().orderValuesBy(Ordering.natural())
                .putAll(Futures.allAsList(results).get()).build();
    } finally {
        exec.shutdown();
    }
}

From source file:com.github.charithe.kafka.KafkaHelper.java

/**
 * Attempt to consume the specified number of messages
 *
 * @param topic                Topic to consume
 * @param consumer             Consumer to use
 * @param numMessagesToConsume Number of messages to consume
 * @param <K>                  Type of Key
 * @param <V>                  Type of Value
 * @return ListenableFuture// w  ww.j  a va 2s .  com
 */
public <K, V> ListenableFuture<List<ConsumerRecord<K, V>>> consume(String topic, KafkaConsumer<K, V> consumer,
        int numMessagesToConsume) {
    consumer.subscribe(Lists.newArrayList(topic));
    ListeningExecutorService executor = MoreExecutors.listeningDecorator(Executors.newSingleThreadExecutor());
    return executor.submit(new RecordConsumer<>(numMessagesToConsume, consumer));
}

From source file:com.google.cloud.dataflow.sdk.io.FileBasedSource.java

private static long getExactTotalSizeOfFiles(Collection<String> files, IOChannelFactory ioChannelFactory)
        throws Exception {
    List<ListenableFuture<Long>> futures = new ArrayList<>();
    ListeningExecutorService service = MoreExecutors
            .listeningDecorator(Executors.newFixedThreadPool(THREAD_POOL_SIZE));
    long totalSize = 0;
    try {//  ww  w .ja  v a  2 s . com
        for (String file : files) {
            futures.add(createFutureForSizeEstimation(file, ioChannelFactory, service));
        }

        for (Long val : Futures.allAsList(futures).get()) {
            totalSize += val;
        }

        return totalSize;
    } finally {
        service.shutdown();
    }
}

From source file:com.ec.android.module.bluetooth40.base.BaseBluetoothControlWithProtocolActivity.java

private void initFuture() {
    //?//from   w ww . ja va2s  .c o m
    ExecutorService mSingleExecutorService = Executors.newSingleThreadExecutor();

    mListeningExecutorService = MoreExecutors.listeningDecorator(mSingleExecutorService);
}

From source file:com.spotify.apollo.core.ServiceImpl.java

ListeningScheduledExecutorService createScheduledExecutorService(Closer closer) {
    final ListeningScheduledExecutorService scheduledExecutorService = MoreExecutors.listeningDecorator(
            Executors.newScheduledThreadPool(Math.max(Runtime.getRuntime().availableProcessors(), 2),
                    new ThreadFactoryBuilder().setNameFormat(serviceName + "-scheduled-%d").build()));
    closer.register(asCloseable(scheduledExecutorService));
    return scheduledExecutorService;
}

From source file:com.google.sha1coin.net.discovery.TorDiscovery.java

private synchronized void createThreadPool(int size) {
    threadPool = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(size));
}