本文整理匯總了Java中com.google.common.util.concurrent.ListeningExecutorService.shutdown方法的典型用法代碼示例。如果您正苦於以下問題:Java ListeningExecutorService.shutdown方法的具體用法?Java ListeningExecutorService.shutdown怎麽用?Java ListeningExecutorService.shutdown使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類com.google.common.util.concurrent.ListeningExecutorService
的用法示例。
在下文中一共展示了ListeningExecutorService.shutdown方法的13個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: testConcurrentFetchTasks
import com.google.common.util.concurrent.ListeningExecutorService; //導入方法依賴的package包/類
@Test
public void testConcurrentFetchTasks() throws Exception {
// Test for regression of AURORA-1625
ListeningExecutorService executor =
MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(5));
assertStoreContents();
saveTasks(TASK_A, TASK_B, TASK_C, TASK_D);
List<ListenableFuture<Integer>> futures = Lists.newArrayList();
for (int i = 0; i < 100; i++) {
futures.add(executor.submit(() -> Iterables.size(fetchTasks(Query.unscoped()))));
}
Future<List<Integer>> f = Futures.allAsList(futures);
executor.shutdown();
executor.awaitTermination(1, TimeUnit.MINUTES);
assertEquals(Iterables.getOnlyElement(ImmutableSet.copyOf(f.get())), (Integer) 4);
}
示例2: shutdown
import com.google.common.util.concurrent.ListeningExecutorService; //導入方法依賴的package包/類
private void shutdown(@Nullable final ListeningExecutorService executorService) {
if (executorService != null) {
executorService.shutdown();
try {
// Wait a while for existing tasks to terminate
if (!executorService.awaitTermination(60, TimeUnit.SECONDS)) {
executorService.shutdownNow(); // Cancel currently executing tasks
// Wait a while for tasks to respond to being cancelled
if (!executorService.awaitTermination(60, TimeUnit.SECONDS)) {
log.warn("Thread pool for metacat refresh did not terminate");
}
}
} catch (InterruptedException ie) {
// (Re-)Cancel if current thread also interrupted
executorService.shutdownNow();
// Preserve interrupt status
Thread.currentThread().interrupt();
}
}
}
示例3: processFastqs
import com.google.common.util.concurrent.ListeningExecutorService; //導入方法依賴的package包/類
/**
* Counts yield and q30 of fastqs in the fastqsPerSample multimap, using 1 thread per file.
* The yield and q30 of the Undetermined sample will count towards the total yield and q30 of the flowcell.
*
* @param fastqsPerSample multimap of sampleName and fastqs to process
* @param threadCount number of maximum threads
* @return FastqTracker with yield and q30 stats for the fastqs processed.
*/
@NotNull
static FastqTracker processFastqs(@NotNull final Multimap<String, File> fastqsPerSample, final int threadCount)
throws InterruptedException {
LOGGER.info("Using " + threadCount + " threads. Processing " + fastqsPerSample.size() + " fastQ files.");
final FastqTrackerWrapper tracker = new FastqTrackerWrapper();
final ListeningExecutorService threadPool = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(threadCount));
for (final String sampleName : fastqsPerSample.keySet()) {
final Collection<File> fastqs = fastqsPerSample.get(sampleName);
for (final File fastq : fastqs) {
final String laneName = getLaneName(fastq);
final ListenableFuture<FastqData> futureResult = threadPool.submit(() -> processFile(fastq));
addCallback(futureResult, (data) -> tracker.addDataFromSampleFile(sampleName, laneName, data),
(error) -> LOGGER.error("Failed to process file: " + fastq.getName(), error));
}
}
threadPool.shutdown();
threadPool.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
return tracker.tracker();
}
示例4: transactionMarker
import com.google.common.util.concurrent.ListeningExecutorService; //導入方法依賴的package包/類
@Override
public void transactionMarker() throws Exception {
ListeningExecutorService executor =
MoreExecutors.listeningDecorator(Executors.newCachedThreadPool());
ListenableFuture<Void> future1 = executor.submit(new Callable<Void>() {
@Override
public Void call() throws InterruptedException {
Thread.sleep(100);
return null;
}
});
future1.addListener(new Runnable() {
@Override
public void run() {
new CreateTraceEntry().traceEntryMarker();
}
}, executor);
Thread.sleep(200);
executor.shutdown();
executor.awaitTermination(10, SECONDS);
}
示例5: guava
import com.google.common.util.concurrent.ListeningExecutorService; //導入方法依賴的package包/類
@Benchmark
public void guava() throws Exception {
final ExecutorService executor = Executors.newWorkStealingPool(THREAD_COUNT);
final ListeningExecutorService listeningExecutor = MoreExecutors.listeningDecorator(executor);
final List<ListenableFuture<Integer>> futures = new ArrayList<>();
for (int i = 0; i < SIZE; i++) {
final int current = i;
futures.add(listeningExecutor.submit(() -> current));
}
int sum = 0;
for (final ListenableFuture<Integer> future : futures) {
sum += future.get();
}
if (sum != EXPECTED_SUM) {
throw new IllegalStateException("did not properly collect all values");
}
listeningExecutor.shutdown();
}
示例6: sendCoins
import com.google.common.util.concurrent.ListeningExecutorService; //導入方法依賴的package包/類
public ListenableFuture<Transaction> sendCoins(final Address address, final Coin amount) {
ExecutorService executor = Executors.newSingleThreadExecutor(bitcoinjThreadFactory);
ListeningExecutorService sendCoinsExecutor = MoreExecutors.listeningDecorator(executor);
ListenableFuture<Transaction> txFuture = sendCoinsExecutor.submit(new Callable<Transaction>() {
@Override
public Transaction call() throws Exception {
BitcoinURI payment = new BitcoinURI(BitcoinURI.convertToBitcoinURI(address, amount, null, null));
CLTVInstantPaymentStep step = new CLTVInstantPaymentStep(walletServiceBinder, payment);
step.process(null);
Transaction fullySignedTx = step.getTransaction();
maybeCommitAndBroadcastTransaction(fullySignedTx);
Log.i(TAG, "Send Coins - address=" + address + ", amount=" + amount
+ ", txHash=" + fullySignedTx.getHashAsString());
return fullySignedTx;
}
});
sendCoinsExecutor.shutdown();
Futures.addCallback(txFuture, new FutureCallback<Transaction>() {
@Override
public void onSuccess(Transaction result) {
Log.i(TAG, "sendCoins - onSuccess - tx " + result.getHashAsString());
broadcastInstantPaymentSuccess();
}
@Override
public void onFailure(Throwable t) {
Log.e(TAG, "sendCoins - onFailure - failed with the following throwable: ", t);
broadcastInstantPaymentFailure();
}
});
return txFuture;
}
示例7: simulateRollout
import com.google.common.util.concurrent.ListeningExecutorService; //導入方法依賴的package包/類
@Override
public ImmutableMap<PreFlopHandType, IncomeRate> simulateRollout( ImmutableMap<PreFlopHandType, IncomeRate> handTypeToIncomeRate, double tolerance, PrintWriter printWriter, int iteration) throws Exception
{
if(printWriter != null)
{
synchronized (printWriter)
{
printWriter.println("HandType, Income Rate, Error, SD, Iteration");
printWriter.flush();
}
}
ImmutableSortedSet<PreFlopHandType> preflopHands = adaptor.adaptDeck(deckFactory.build());
ImmutableMap.Builder<PreFlopHandType, IncomeRate> newIncomeRateBuilder = ImmutableMap.builder();
int numCores = Runtime.getRuntime().availableProcessors();
ListeningExecutorService threadPool = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(numCores));
for(PreFlopHandType handType : preflopHands)
{
IDeck deck = deckFactory.build();
IncomeRateSimulationExecutor executor = new IncomeRateSimulationExecutor(handType, deck, handTypeToIncomeRate, tolerance, printWriter, iteration);
ListenableFuture<IncomeRate> future = threadPool.submit(( Callable<IncomeRate>) executor );
}
threadPool.shutdown();
threadPool.awaitTermination(1, TimeUnit.DAYS);
return newIncomeRateBuilder.build();
}
示例8: callLightblueSvc
import com.google.common.util.concurrent.ListeningExecutorService; //導入方法依賴的package包/類
private <T> ListenableFuture<T> callLightblueSvc(final Method method, final Object[] values, final FacadeOperation op, final MethodCallStringifier callStringifier) {
ListeningExecutorService executor = createExecutor();
try {
// fetch from lightblue using future (asynchronously)
final long parentThreadId = Thread.currentThread().getId();
return executor.submit(new Callable<T>(){
@Override
public T call() throws Exception {
Timer dest = new Timer("destination."+method.getName());
if (sharedStore != null) {
sharedStore.copyFromThread(parentThreadId);
}
try {
return (T) method.invoke(lightblueSvc, values);
} catch (Throwable t) {
if (shouldSource(op) && shouldCheckConsistency(op)) {
// swallow lightblue exception if legacy was called and consistency checker is on
log.warn("Lightblue call " + implementationName + "." + callStringifier + " threw an exception. Returning data from legacy.", t);
onExceptionSwallowed(t);
throw new SwallowableException(t, true);
} else {
// throw lightblue exception if legacy was not called or consistency checker is disabled
throw new SwallowableException(t, false);
}
} finally {
long callTook = dest.complete();
long slowWarning = timeoutConfiguration.getSlowWarningMS(method.getName(), op);
if (callTook >= slowWarning) {
// call is slow; this will log even if source fails to respond
log.warn("Slow call warning: {}.{} took {}ms",implementationName, callStringifier.toString(), callTook);
}
}
}
});
} finally {
executor.shutdown();
}
}
示例9: fourKindsOfRequestAtOnce
import com.google.common.util.concurrent.ListeningExecutorService; //導入方法依賴的package包/類
@Test
public void fourKindsOfRequestAtOnce() throws Exception {
RxGreeterGrpc.RxGreeterStub stub = RxGreeterGrpc.newRxStub(channel);
// == MAKE REQUESTS ==
// One to One
Single<HelloRequest> req1 = Single.just(HelloRequest.newBuilder().setName("rxjava").build());
Single<HelloResponse> resp1 = stub.sayHello(req1);
// One to Many
Single<HelloRequest> req2 = Single.just(HelloRequest.newBuilder().setName("rxjava").build());
Flowable<HelloResponse> resp2 = stub.sayHelloRespStream(req2);
// Many to One
Flowable<HelloRequest> req3 = Flowable.just(
HelloRequest.newBuilder().setName("a").build(),
HelloRequest.newBuilder().setName("b").build(),
HelloRequest.newBuilder().setName("c").build());
Single<HelloResponse> resp3 = stub.sayHelloReqStream(req3);
// Many to Many
Flowable<HelloRequest> req4 = Flowable.just(
HelloRequest.newBuilder().setName("a").build(),
HelloRequest.newBuilder().setName("b").build(),
HelloRequest.newBuilder().setName("c").build(),
HelloRequest.newBuilder().setName("d").build(),
HelloRequest.newBuilder().setName("e").build());
Flowable<HelloResponse> resp4 = stub.sayHelloBothStream(req4);
// == VERIFY RESPONSES ==
ListeningExecutorService executorService = MoreExecutors.listeningDecorator(Executors.newCachedThreadPool());
// Run all four verifications in parallel
try {
// One to One
ListenableFuture<Boolean> oneToOne = executorService.submit(() -> {
TestObserver<String> testObserver1 = resp1.map(HelloResponse::getMessage).test();
testObserver1.awaitTerminalEvent(1, TimeUnit.SECONDS);
testObserver1.assertValue("Hello rxjava");
return true;
});
// One to Many
ListenableFuture<Boolean> oneToMany = executorService.submit(() -> {
TestSubscriber<String> testSubscriber1 = resp2.map(HelloResponse::getMessage).test();
testSubscriber1.awaitTerminalEvent(1, TimeUnit.SECONDS);
testSubscriber1.assertValues("Hello rxjava", "Hi rxjava", "Greetings rxjava");
return true;
});
// Many to One
ListenableFuture<Boolean> manyToOne = executorService.submit(() -> {
TestObserver<String> testObserver2 = resp3.map(HelloResponse::getMessage).test();
testObserver2.awaitTerminalEvent(1, TimeUnit.SECONDS);
testObserver2.assertValue("Hello a and b and c");
return true;
});
// Many to Many
ListenableFuture<Boolean> manyToMany = executorService.submit(() -> {
TestSubscriber<String> testSubscriber2 = resp4.map(HelloResponse::getMessage).test();
testSubscriber2.awaitTerminalEvent(1, TimeUnit.SECONDS);
testSubscriber2.assertValues("Hello a and b", "Hello c and d", "Hello e");
testSubscriber2.assertComplete();
return true;
});
ListenableFuture<List<Boolean>> allFutures = Futures.allAsList(Lists.newArrayList(oneToOne, oneToMany, manyToOne, manyToMany));
// Block for response
List<Boolean> results = allFutures.get(3, TimeUnit.SECONDS);
assertThat(results).containsExactly(true, true, true, true);
} finally {
executorService.shutdown();
}
}
示例10: fourKindsOfRequestAtOnce
import com.google.common.util.concurrent.ListeningExecutorService; //導入方法依賴的package包/類
@Test
public void fourKindsOfRequestAtOnce() throws Exception {
StepVerifier.setDefaultTimeout(Duration.ofSeconds(3));
ReactorGreeterGrpc.ReactorGreeterStub stub = ReactorGreeterGrpc.newReactorStub(channel);
// == MAKE REQUESTS ==
// One to One
Mono<HelloRequest> req1 = Mono.just(HelloRequest.newBuilder().setName("reactorjava").build());
Mono<HelloResponse> resp1 = stub.sayHello(req1);
// One to Many
Mono<HelloRequest> req2 = Mono.just(HelloRequest.newBuilder().setName("reactorjava").build());
Flux<HelloResponse> resp2 = stub.sayHelloRespStream(req2);
// Many to One
Flux<HelloRequest> req3 = Flux.just(
HelloRequest.newBuilder().setName("a").build(),
HelloRequest.newBuilder().setName("b").build(),
HelloRequest.newBuilder().setName("c").build());
Mono<HelloResponse> resp3 = stub.sayHelloReqStream(req3);
// Many to Many
Flux<HelloRequest> req4 = Flux.just(
HelloRequest.newBuilder().setName("a").build(),
HelloRequest.newBuilder().setName("b").build(),
HelloRequest.newBuilder().setName("c").build(),
HelloRequest.newBuilder().setName("d").build(),
HelloRequest.newBuilder().setName("e").build());
Flux<HelloResponse> resp4 = stub.sayHelloBothStream(req4);
// == VERIFY RESPONSES ==
ListeningExecutorService executorService = MoreExecutors.listeningDecorator(Executors.newCachedThreadPool());
// Run all four verifications in parallel
try {
// One to One
ListenableFuture<Boolean> oneToOne = executorService.submit(() -> {
StepVerifier.create(resp1.map(HelloResponse::getMessage))
.expectNext("Hello reactorjava")
.verifyComplete();
return true;
});
// One to Many
ListenableFuture<Boolean> oneToMany = executorService.submit(() -> {
StepVerifier.create(resp2.map(HelloResponse::getMessage))
.expectNext("Hello reactorjava", "Hi reactorjava", "Greetings reactorjava")
.verifyComplete();
return true;
});
// Many to One
ListenableFuture<Boolean> manyToOne = executorService.submit(() -> {
StepVerifier.create(resp3.map(HelloResponse::getMessage))
.expectNext("Hello a and b and c")
.verifyComplete();
return true;
});
// Many to Many
ListenableFuture<Boolean> manyToMany = executorService.submit(() -> {
StepVerifier.create(resp4.map(HelloResponse::getMessage))
.expectNext("Hello a and b", "Hello c and d", "Hello e")
.verifyComplete();
return true;
});
ListenableFuture<List<Boolean>> allFutures = Futures.allAsList(Lists.newArrayList(oneToOne, oneToMany, manyToOne, manyToMany));
// Block for response
List<Boolean> results = allFutures.get(3, TimeUnit.SECONDS);
assertThat(results).containsExactly(true, true, true, true);
} finally {
executorService.shutdown();
}
}
示例11: collectRefund
import com.google.common.util.concurrent.ListeningExecutorService; //導入方法依賴的package包/類
public ListenableFuture<Transaction> collectRefund(final Address sendTo) {
/*
* Bitcoin nodes consider the median time of the last couple of blocks when
* comparing the nLockTime (BIP 113). The median time is behind the current
* time (unix seconds). As a consequence, a transaction is not relayed
* by the nodes even though the lock time expired, i.e. lockTime < currentTime.
* The median lags behind ~1h. In other words, a transaction with lock time t should be
* broadcasted not earlier than t+1h. Otherwise, the transaction must be re-broadcasted
* and it takes a long time for the transaction to be included in a block.
* - https://bitcoincore.org/en/releases/0.12.1/
* - https://github.com/bitcoin/bips/blob/master/bip-0113.mediawiki
*/
ExecutorService executor = Executors.newSingleThreadExecutor(bitcoinjThreadFactory);
ListeningExecutorService collectRefundExecutor = MoreExecutors.listeningDecorator(executor);
ListenableFuture<Transaction> txFuture = collectRefundExecutor.submit(new Callable<Transaction>() {
@Override
public Transaction call() throws Exception {
final List<TransactionOutput> unlockedTxOut = getUnlockedUnspentOutputs();
Transaction transaction = BitcoinUtils.createSpendAllTx(
getNetworkParameters(),
unlockedTxOut,
sendTo);
// since we sign with 1 key (without server key), we need to set
// the nLockTime and sequence number flags of CLTV inputs.
Map<String, Long> timeLocksOfInputs = createLockTimeForInputsMap(transaction.getInputs());
BitcoinUtils.setFlagsOfCLTVInputs(
transaction,
timeLocksOfInputs,
org.bitcoinj.core.Utils.currentTimeSeconds());
// code is very similar to signTransaction, but we use a different scriptSig!
final List<TransactionInput> inputs = transaction.getInputs();
for (int i = 0; i < inputs.size(); ++i) {
TransactionInput txIn = inputs.get(i);
TransactionOutput prevTxOut = txIn.getConnectedOutput();
byte[] sentToHash = prevTxOut.getScriptPubKey().getPubKeyHash();
TimeLockedAddress tla = findTimeLockedAddressByHash(sentToHash);
if (tla == null) {
throw new CoinbleskException(String.format(Locale.US,
"Signing error: did not find redeem script for input: %s, ", txIn));
}
byte[] redeemScript = tla.createRedeemScript().getProgram();
TransactionSignature signature = transaction.calculateSignature(
i, multisigClientKey, redeemScript, Transaction.SigHash.ALL, false);
Script scriptSig = tla.createScriptSigAfterLockTime(signature);
txIn.setScriptSig(scriptSig);
}
BitcoinUtils.verifyTxFull(transaction);
commitAndBroadcastTransaction(transaction);
Coin amount = transaction.getOutputSum();
Log.i(TAG, "Collect Refund - address=" + sendTo + ", amount=" + amount
+ ", txHash=" + transaction.getHashAsString());
return transaction;
}
});
collectRefundExecutor.shutdown();
Futures.addCallback(txFuture, new FutureCallback<Transaction>() {
@Override
public void onSuccess(Transaction result) {
Log.i(TAG, "collectRefund - onSuccess - tx " + result.getHashAsString());
broadcastInstantPaymentSuccess();
}
@Override
public void onFailure(Throwable t) {
Log.e(TAG, "collectRefund - onFailure - failed with the following throwable: ", t);
broadcastInstantPaymentFailure();
}
});
return txFuture;
}
示例12: initialize
import com.google.common.util.concurrent.ListeningExecutorService; //導入方法依賴的package包/類
public static TasmoServiceHandle<ReadMaterializerViewFields> initialize(TasmoReadMaterializerConfig config,
TasmoViewModel tasmoViewModel,
WrittenEventProvider writtenEventProvider,
TasmoStorageProvider tasmoStorageProvider) throws Exception {
ConcurrencyStore concurrencyStore = new HBaseBackedConcurrencyStore(tasmoStorageProvider.concurrencyStorage());
ReferenceStore referenceStore = new ReferenceStore(concurrencyStore,
tasmoStorageProvider.multiLinksStorage(),
tasmoStorageProvider.multiBackLinksStorage());
// TODO add config option to switch between batching and serial.
ReferenceTraverser referenceTraverser = new SerialReferenceTraverser(referenceStore);
EventValueStore eventValueStore = new EventValueStore(concurrencyStore, tasmoStorageProvider.eventStorage());
FieldValueReader fieldValueReader = new EventValueStoreFieldValueReader(eventValueStore);
ThreadFactory eventProcessorThreadFactory = new ThreadFactoryBuilder()
.setNameFormat("view-read-materialization-processor-%d")
.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread t, Throwable e) {
LOG.error("Thread " + t.getName() + " threw uncaught exception", e);
}
})
.build();
ExecutorService processorThreads = Executors.newFixedThreadPool(config.getNumberOfViewRequestProcessorThreads(), eventProcessorThreadFactory);
final ListeningExecutorService listeningDecorator = MoreExecutors.listeningDecorator(processorThreads);
final ReadMaterializerViewFields readMaterializer = new ReadMaterializerViewFields(referenceTraverser,
fieldValueReader, concurrencyStore, tasmoViewModel, listeningDecorator);
return new TasmoServiceHandle<ReadMaterializerViewFields>() {
@Override
public ReadMaterializerViewFields getService() {
return readMaterializer;
}
@Override
public void start() throws Exception {
}
@Override
public void stop() throws Exception {
listeningDecorator.shutdown();
}
};
}
示例13: completable
import com.google.common.util.concurrent.ListeningExecutorService; //導入方法依賴的package包/類
@Benchmark
public void completable() throws Exception {
final ExecutorService executor = Executors.newFixedThreadPool(THREAD_COUNT);
final ListeningExecutorService listeningExecutor = MoreExecutors.listeningDecorator(executor);
final AtomicInteger sum = new AtomicInteger();
final CountDownLatch latch = new CountDownLatch(1);
final CountDownLatch tasks = new CountDownLatch(CALLBACK_COUNT * SIZE);
final FutureCallback<Integer> callback = new FutureCallback<Integer>() {
@Override
public void onSuccess(Integer result) {
sum.addAndGet(result);
tasks.countDown();
}
@Override
public void onFailure(Throwable t) {
}
};
for (int i = 0; i < SIZE; i++) {
final int current = i;
final ListenableFuture<Integer> future = listeningExecutor.submit(() -> {
latch.await();
return current;
});
for (int c = 0; c < CALLBACK_COUNT; c++) {
com.google.common.util.concurrent.Futures.addCallback(future, callback);
}
}
latch.countDown();
tasks.await(1, TimeUnit.SECONDS);
if (sum.get() != EXPECTED_SUM) {
throw new IllegalStateException(
String.format("did not properly collect all values: expected %d, but was %d",
EXPECTED_SUM, sum.get()));
}
listeningExecutor.shutdown();
}