当前位置: 首页>>代码示例>>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;未经允许,请勿转载。