當前位置: 首頁>>代碼示例>>Java>>正文


Java MoreExecutors類代碼示例

本文整理匯總了Java中com.google.common.util.concurrent.MoreExecutors的典型用法代碼示例。如果您正苦於以下問題:Java MoreExecutors類的具體用法?Java MoreExecutors怎麽用?Java MoreExecutors使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


MoreExecutors類屬於com.google.common.util.concurrent包,在下文中一共展示了MoreExecutors類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: testAddListener

import com.google.common.util.concurrent.MoreExecutors; //導入依賴的package包/類
@Test
public void testAddListener() throws Exception {
  Task<String> task = Tasks.forResult("test");
  ApiFuture<String> future = new TaskToApiFuture<>(task);
  final AtomicBoolean result = new AtomicBoolean(false);
  future.addListener(new Runnable() {
    @Override
    public void run() {
      result.set(true);
    }
  }, MoreExecutors.directExecutor());
  assertEquals("test", future.get());
  assertTrue(result.get());
  assertFalse(future.isCancelled());
  assertTrue(future.isDone());
}
 
開發者ID:firebase,項目名稱:firebase-admin-java,代碼行數:17,代碼來源:TaskToApiFutureTest.java

示例2: broadcastTransactions

import com.google.common.util.concurrent.MoreExecutors; //導入依賴的package包/類
/**
 * Broadcasts the list of signed transactions.
 * @param transactionsRaw transactions in raw byte[] format
 */
public ArrayList<Transaction> broadcastTransactions(ArrayList<byte[]> transactionsRaw) {
    ArrayList<Transaction> transactions = new ArrayList<>();
    for (byte[] transactionRaw : transactionsRaw) {
        final Wallet.SendResult result = new Wallet.SendResult();
        result.tx = new Transaction(params, transactionRaw);

        result.broadcast = kit.peerGroup().broadcastTransaction(result.tx);
        result.broadcastComplete = result.broadcast.future();

        result.broadcastComplete.addListener(new Runnable() {
            @Override
            public void run() {
                System.out.println("Asset spent! txid: " + result.tx.getHashAsString());
            }
        }, MoreExecutors.directExecutor());

        transactions.add(result.tx);
    }
    return transactions;
}
 
開發者ID:digital-voting-pass,項目名稱:polling-station-app,代碼行數:25,代碼來源:BlockChain.java

示例3: main

import com.google.common.util.concurrent.MoreExecutors; //導入依賴的package包/類
public static void main(String... args) {
  MongoClient client = new MongoClient("localhost");
  RepositorySetup setup = RepositorySetup.builder()
      .database(client.getDatabase("test"))
      .executor(MoreExecutors.listeningDecorator(Executors.newCachedThreadPool()))
      .gson(new GsonBuilder()
          .registerTypeAdapterFactory(new GsonAdaptersEnt())
          .create())
      .build();

  EntRepository repository = new EntRepository(setup);

  EntRepository.Criteria where = repository.criteria()
      .uuid("8b7a881c-6ccb-4ada-8f6a-60cc99e6aa20")
      .actionIn("BAN", "IPBAN");

  Criteria or = where.expiresAbsent()
      .or()
      .with(where)
      .expiresGreaterThan(TimeInstant.of(1467364749679L));

  System.out.println(or);

  repository.find(or).fetchAll().getUnchecked();
}
 
開發者ID:weiwenqiang,項目名稱:GitHub,代碼行數:26,代碼來源:Ent.java

示例4: setUp

import com.google.common.util.concurrent.MoreExecutors; //導入依賴的package包/類
@Setup(Level.Trial)
@Override
public void setUp() throws Exception {
    ListeningExecutorService dsExec = MoreExecutors.newDirectExecutorService();
    executor = MoreExecutors.listeningDecorator(
            MoreExecutors.getExitingExecutorService((ThreadPoolExecutor) Executors.newFixedThreadPool(1), 1L,
                    TimeUnit.SECONDS));

    InMemoryDOMDataStore operStore = new InMemoryDOMDataStore("OPER", dsExec);
    InMemoryDOMDataStore configStore = new InMemoryDOMDataStore("CFG", dsExec);
    Map<LogicalDatastoreType, DOMStore> datastores = ImmutableMap.of(
        LogicalDatastoreType.OPERATIONAL, (DOMStore)operStore,
        LogicalDatastoreType.CONFIGURATION, configStore);

    domBroker = new SerializedDOMDataBroker(datastores, executor);
    schemaContext = BenchmarkModel.createTestContext();
    configStore.onGlobalContextUpdated(schemaContext);
    operStore.onGlobalContextUpdated(schemaContext);
    initTestNode();
}
 
開發者ID:hashsdn,項目名稱:hashsdn-controller,代碼行數:21,代碼來源:InMemoryBrokerWriteTransactionBenchmark.java

示例5: testSValue

import com.google.common.util.concurrent.MoreExecutors; //導入依賴的package包/類
@Test
public void testSValue() throws Exception {
    // Check that we never generate an S value that is larger than half the curve order. This avoids a malleability
    // issue that can allow someone to change a transaction [hash] without invalidating the signature.
    final int ITERATIONS = 10;
    ListeningExecutorService executor = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(ITERATIONS));
    List<ListenableFuture<ECKey.ECDSASignature>> sigFutures = Lists.newArrayList();
    final ECKey key = new ECKey();
    for (byte i = 0; i < ITERATIONS; i++) {
        final byte[] hash = HashUtil.sha3(new byte[]{i});
        sigFutures.add(executor.submit(new Callable<ECKey.ECDSASignature>() {
            @Override
            public ECKey.ECDSASignature call() throws Exception {
                return key.doSign(hash);
            }
        }));
    }
    List<ECKey.ECDSASignature> sigs = Futures.allAsList(sigFutures).get();
    for (ECKey.ECDSASignature signature : sigs) {
        assertTrue(signature.s.compareTo(ECKey.HALF_CURVE_ORDER) <= 0);
    }
    final ECKey.ECDSASignature duplicate = new ECKey.ECDSASignature(sigs.get(0).r, sigs.get(0).s);
    assertEquals(sigs.get(0), duplicate);
    assertEquals(sigs.get(0).hashCode(), duplicate.hashCode());
}
 
開發者ID:talentchain,項目名稱:talchain,代碼行數:26,代碼來源:ECKeyTest.java

示例6: start

import com.google.common.util.concurrent.MoreExecutors; //導入依賴的package包/類
public synchronized void start(CommandExecutor commandExecutor) {
    if (isStarted()) {
        return;
    }

    this.commandExecutor = requireNonNull(commandExecutor, "commandExecutor");

    scheduler = MoreExecutors.listeningDecorator(Executors.newSingleThreadScheduledExecutor(
            new DefaultThreadFactory("mirroring-scheduler", true)));

    worker = MoreExecutors.listeningDecorator(
            new ThreadPoolExecutor(0, numThreads, 1, TimeUnit.MINUTES, new SynchronousQueue<>(),
                                   new DefaultThreadFactory("mirroring-worker", true)));

    final ListenableScheduledFuture<?> future = scheduler.scheduleWithFixedDelay(
            this::schedulePendingMirrors,
            TICK.getSeconds(), TICK.getSeconds(), TimeUnit.SECONDS);

    FuturesExtra.addFailureCallback(
            future,
            cause -> logger.error("Git-to-CD mirroring scheduler stopped due to an unexpected exception:",
                                  cause));
}
 
開發者ID:line,項目名稱:centraldogma,代碼行數:24,代碼來源:DefaultMirroringService.java

示例7: backupDatastore

import com.google.common.util.concurrent.MoreExecutors; //導入依賴的package包/類
@Override
public Future<RpcResult<Void>> backupDatastore(final BackupDatastoreInput input) {
    LOG.debug("backupDatastore: {}", input);

    if (Strings.isNullOrEmpty(input.getFilePath())) {
        return newFailedRpcResultFuture("A valid file path must be specified");
    }

    final SettableFuture<RpcResult<Void>> returnFuture = SettableFuture.create();
    ListenableFuture<List<DatastoreSnapshot>> future = sendMessageToShardManagers(GetSnapshot.INSTANCE);
    Futures.addCallback(future, new FutureCallback<List<DatastoreSnapshot>>() {
        @Override
        public void onSuccess(List<DatastoreSnapshot> snapshots) {
            saveSnapshotsToFile(new DatastoreSnapshotList(snapshots), input.getFilePath(), returnFuture);
        }

        @Override
        public void onFailure(Throwable failure) {
            onDatastoreBackupFailure(input.getFilePath(), returnFuture, failure);
        }
    }, MoreExecutors.directExecutor());

    return returnFuture;
}
 
開發者ID:hashsdn,項目名稱:hashsdn-controller,代碼行數:25,代碼來源:ClusterAdminRpcService.java

示例8: prepare

import com.google.common.util.concurrent.MoreExecutors; //導入依賴的package包/類
@Override
public ListenableFuture<Void> prepare() {
    LOG.debug("Preparing transaction for shard {}", shardRoot);

    checkTransactionReadied();
    final List<ListenableFuture<Void>> futures =
            cohorts.stream().map(DOMStoreThreePhaseCommitCohort::preCommit).collect(Collectors.toList());
    final SettableFuture<Void> ret = SettableFuture.create();

    Futures.addCallback(Futures.allAsList(futures), new FutureCallback<List<Void>>() {
        @Override
        public void onSuccess(final List<Void> result) {
            ret.set(null);
        }

        @Override
        public void onFailure(final Throwable throwable) {
            ret.setException(throwable);
        }
    }, MoreExecutors.directExecutor());

    return ret;
}
 
開發者ID:hashsdn,項目名稱:hashsdn-controller,代碼行數:24,代碼來源:ShardProxyTransaction.java

示例9: getDefaultCommitExecutor

import com.google.common.util.concurrent.MoreExecutors; //導入依賴的package包/類
/**
 * @deprecated This method is only used from configuration modules and thus callers of it
 *             should use service injection to make the executor configurable.
 */
@Deprecated
public static synchronized ListeningExecutorService getDefaultCommitExecutor() {
    if (COMMIT_EXECUTOR == null) {
        final ThreadFactory factory = new ThreadFactoryBuilder().setDaemon(true).setNameFormat("md-sal-binding-commit-%d").build();
        /*
         * FIXME: this used to be newCacheThreadPool(), but MD-SAL does not have transaction
         *        ordering guarantees, which means that using a concurrent threadpool results
         *        in application data being committed in random order, potentially resulting
         *        in inconsistent data being present. Once proper primitives are introduced,
         *        concurrency can be reintroduced.
         */
        final ExecutorService executor = Executors.newSingleThreadExecutor(factory);
        COMMIT_EXECUTOR = MoreExecutors.listeningDecorator(executor);
    }

    return COMMIT_EXECUTOR;
}
 
開發者ID:hashsdn,項目名稱:hashsdn-controller,代碼行數:22,代碼來源:SingletonHolder.java

示例10: setUp

import com.google.common.util.concurrent.MoreExecutors; //導入依賴的package包/類
/**
 * @throws java.lang.Exception
 */
@Before
public void setUp() throws Exception {
    final BindingBrokerTestFactory testFactory = new BindingBrokerTestFactory();
    testFactory.setExecutor(MoreExecutors.newDirectExecutorService());
    testFactory.setStartWithParsedSchema(true);
    testContext = testFactory.getTestContext();

    testContext.start();
    domMountPointService = testContext.getDomMountProviderService();
    bindingMountPointService = testContext.getBindingMountPointService();
    assertNotNull(domMountPointService);

    final InputStream moduleStream = BindingReflections.getModuleInfo(
            OpendaylightTestRpcServiceService.class)
            .getModuleSourceStream();

    assertNotNull(moduleStream);
    final List<InputStream> rpcModels = Collections.singletonList(moduleStream);
    schemaContext = YangParserTestUtils.parseYangStreams(rpcModels);
}
 
開發者ID:hashsdn,項目名稱:hashsdn-controller,代碼行數:24,代碼來源:DOMRpcServiceTestBugfix560.java

示例11: testSValue

import com.google.common.util.concurrent.MoreExecutors; //導入依賴的package包/類
@Test
public void testSValue() throws Exception {
    // Check that we never generate an S value that is larger than half the curve order. This avoids a malleability
    // issue that can allow someone to change a transaction [hash] without invalidating the signature.
    final int ITERATIONS = 10;
    ListeningExecutorService executor = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(ITERATIONS));
    List<ListenableFuture<ECKey.ECDSASignature>> sigFutures = Lists.newArrayList();
    final ECKey key = new ECKey();
    for (byte i = 0; i < ITERATIONS; i++) {
        final byte[] hash = HashUtil.sha3(new byte[]{i});
        sigFutures.add(executor.submit(new Callable<ECDSASignature>() {
            @Override
            public ECKey.ECDSASignature call() throws Exception {
                return key.doSign(hash);
            }
        }));
    }
    List<ECKey.ECDSASignature> sigs = Futures.allAsList(sigFutures).get();
    for (ECKey.ECDSASignature signature : sigs) {
        assertTrue(signature.s.compareTo(ECKey.HALF_CURVE_ORDER) <= 0);
    }
    final ECKey.ECDSASignature duplicate = new ECKey.ECDSASignature(sigs.get(0).r, sigs.get(0).s);
    assertEquals(sigs.get(0), duplicate);
    assertEquals(sigs.get(0).hashCode(), duplicate.hashCode());
}
 
開發者ID:rsksmart,項目名稱:rskj,代碼行數:26,代碼來源:ECKeyTest.java

示例12: forwardCoins

import com.google.common.util.concurrent.MoreExecutors; //導入依賴的package包/類
private static void forwardCoins(Transaction tx) {
    try {
        Coin value = tx.getValueSentToMe(kit.wallet());
        System.out.println("Forwarding " + value.toFriendlyString());
        // Now send the coins back! Send with a small fee attached to ensure rapid confirmation.
        final Coin amountToSend = value.subtract(Transaction.REFERENCE_DEFAULT_MIN_TX_FEE);
        final Wallet.SendResult sendResult = kit.wallet().sendCoins(kit.peerGroup(), forwardingAddress, amountToSend);
        checkNotNull(sendResult);  // We should never try to send more coins than we have!
        System.out.println("Sending ...");
        // Register a callback that is invoked when the transaction has propagated across the network.
        // This shows a second style of registering ListenableFuture callbacks, it works when you don't
        // need access to the object the future returns.
        sendResult.broadcastComplete.addListener(new Runnable() {
            @Override
            public void run() {
                // The wallet has changed now, it'll get auto saved shortly or when the app shuts down.
                System.out.println("Sent coins onwards! Transaction hash is " + sendResult.tx.getHashAsString());
            }
        }, MoreExecutors.sameThreadExecutor());
    } catch (KeyCrypterException | InsufficientMoneyException e) {
        // We don't use encrypted wallets in this example - can never happen.
        throw new RuntimeException(e);
    }
}
 
開發者ID:creativechain,項目名稱:creacoinj,代碼行數:25,代碼來源:ForwardingService.java

示例13: getDefaultChangeEventExecutor

import com.google.common.util.concurrent.MoreExecutors; //導入依賴的package包/類
public static ExecutorService getDefaultChangeEventExecutor() {
    if (CHANGE_EVENT_EXECUTOR == null) {
        final ThreadFactory factory = new ThreadFactoryBuilder().setDaemon(true).setNameFormat("md-sal-binding-change-%d").build();
        /*
         * FIXME: this used to be newCacheThreadPool(), but MD-SAL does not have transaction
         *        ordering guarantees, which means that using a concurrent threadpool results
         *        in application data being committed in random order, potentially resulting
         *        in inconsistent data being present. Once proper primitives are introduced,
         *        concurrency can be reintroduced.
         */
        final ExecutorService executor = Executors.newSingleThreadExecutor(factory);
        CHANGE_EVENT_EXECUTOR  = MoreExecutors.listeningDecorator(executor);
    }

    return CHANGE_EVENT_EXECUTOR;
}
 
開發者ID:hashsdn,項目名稱:hashsdn-controller,代碼行數:17,代碼來源:SingletonHolder.java

示例14: testMuxedFileSizeCacheIsEmptyBeforeMuxing

import com.google.common.util.concurrent.MoreExecutors; //導入依賴的package包/類
@Test
public void testMuxedFileSizeCacheIsEmptyBeforeMuxing()
		throws Exception {
	// Given
	mux2fs = new MuxFs(mirrorRoot, tempDir, muxerFactory, sleeper, fileChannelCloser, MoreExecutors.newDirectExecutorService());
	fs = mux2fs;
	StatFiller stat = mock(StatFiller.class);
	Path mkv = mockPath("file.mkv", 700000000L);
	Path srt = mockPath("file.srt", 2000L);
	mockDirectoryStream(mirrorRoot, srt, mkv);
	when(stat.statWithSize(eq(mkv), sizeGetterCaptor.capture(), extraSizeGetterCaptor.capture())).thenReturn(mock(UnixFileStat.class));
	mockAttributes(mkv, 234);
	FileInfo info = FileInfo.of(mkv);
	// When
	int result = fs.getattr("file.mkv", stat);
	// Then
	assertThat(result).isEqualTo(SUCCESS);
	verify(stat).statWithSize(eq(mkv), any(), any());
	verifyNoMoreInteractions(stat);
	assertThat(sizeGetterCaptor.getValue().apply(info)).isEmpty();
	assertThat(extraSizeGetterCaptor.getValue().get()).isEqualTo(2000L);
}
 
開發者ID:tfiskgul,項目名稱:mux2fs,代碼行數:23,代碼來源:MuxFsTest.java

示例15: startNewDomDataBroker

import com.google.common.util.concurrent.MoreExecutors; //導入依賴的package包/類
public void startNewDomDataBroker() {
    checkState(this.executor != null, "Executor needs to be set");
    final InMemoryDOMDataStore operStore = new InMemoryDOMDataStore("OPER",
        MoreExecutors.newDirectExecutorService());
    final InMemoryDOMDataStore configStore = new InMemoryDOMDataStore("CFG",
        MoreExecutors.newDirectExecutorService());
    this.newDatastores = ImmutableMap.<LogicalDatastoreType, DOMStore>builder()
            .put(LogicalDatastoreType.OPERATIONAL, operStore)
            .put(LogicalDatastoreType.CONFIGURATION, configStore)
            .build();

    this.newDOMDataBroker = new SerializedDOMDataBroker(this.newDatastores, this.executor);

    this.mockSchemaService.registerSchemaContextListener(configStore);
    this.mockSchemaService.registerSchemaContextListener(operStore);
}
 
開發者ID:hashsdn,項目名稱:hashsdn-controller,代碼行數:17,代碼來源:BindingTestContext.java


注:本文中的com.google.common.util.concurrent.MoreExecutors類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。