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


Java ListeningExecutorService類代碼示例

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


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

示例1: testSValue

import com.google.common.util.concurrent.ListeningExecutorService; //導入依賴的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

示例2: ApacheThriftMethodInvoker

import com.google.common.util.concurrent.ListeningExecutorService; //導入依賴的package包/類
public ApacheThriftMethodInvoker(
        ListeningExecutorService executorService,
        ListeningScheduledExecutorService delayService,
        TTransportFactory transportFactory,
        TProtocolFactory protocolFactory,
        Duration connectTimeout,
        Duration requestTimeout,
        Optional<HostAndPort> socksProxy,
        Optional<SSLContext> sslContext)
{
    this.executorService = requireNonNull(executorService, "executorService is null");
    this.delayService = requireNonNull(delayService, "delayService is null");
    this.transportFactory = requireNonNull(transportFactory, "transportFactory is null");
    this.protocolFactory = requireNonNull(protocolFactory, "protocolFactory is null");
    this.connectTimeoutMillis = Ints.saturatedCast(requireNonNull(connectTimeout, "connectTimeout is null").toMillis());
    this.requestTimeoutMillis = Ints.saturatedCast(requireNonNull(requestTimeout, "requestTimeout is null").toMillis());
    this.socksProxy = requireNonNull(socksProxy, "socksProxy is null");
    this.sslContext = requireNonNull(sslContext, "sslContext is null");
}
 
開發者ID:airlift,項目名稱:drift,代碼行數:20,代碼來源:ApacheThriftMethodInvoker.java

示例3: testSValue

import com.google.common.util.concurrent.ListeningExecutorService; //導入依賴的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

示例4: dbContext

import com.google.common.util.concurrent.ListeningExecutorService; //導入依賴的package包/類
@Provides
@Singleton
static DSLContext dbContext(
    DataSource dataSource, @ForDatabase ListeningExecutorService dbExecutor) {
  Configuration configuration =
      new DefaultConfiguration()
          .set(dbExecutor)
          .set(SQLDialect.MYSQL)
          .set(new Settings().withRenderSchema(false))
          .set(new DataSourceConnectionProvider(dataSource))
          .set(DatabaseUtil.sfmRecordMapperProvider());
  DSLContext ctx = DSL.using(configuration);
  // Eagerly trigger JOOQ classinit for better startup performance.
  ctx.select().from("curio_server_framework_init").getSQL();
  return ctx;
}
 
開發者ID:curioswitch,項目名稱:curiostack,代碼行數:17,代碼來源:DatabaseModule.java

示例5: setUp

import com.google.common.util.concurrent.ListeningExecutorService; //導入依賴的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

示例6: setupStore

import com.google.common.util.concurrent.ListeningExecutorService; //導入依賴的package包/類
@Before
public void setupStore() {
    InMemoryDOMDataStore operStore = new InMemoryDOMDataStore("OPER", MoreExecutors.newDirectExecutorService());
    InMemoryDOMDataStore configStore = new InMemoryDOMDataStore("CFG", MoreExecutors.newDirectExecutorService());
    schemaContext = TestModel.createTestContext();

    operStore.onGlobalContextUpdated(schemaContext);
    configStore.onGlobalContextUpdated(schemaContext);

    ImmutableMap<LogicalDatastoreType, DOMStore> stores = ImmutableMap.<LogicalDatastoreType, DOMStore> builder() //
            .put(CONFIGURATION, configStore) //
            .put(OPERATIONAL, operStore) //
            .build();
    ListeningExecutorService executor = MoreExecutors.listeningDecorator(Executors.newSingleThreadExecutor());
    domBroker = new SerializedDOMDataBroker(stores, executor);
}
 
開發者ID:hashsdn,項目名稱:hashsdn-controller,代碼行數:17,代碼來源:DOMBrokerPerformanceTest.java

示例7: setupStore

import com.google.common.util.concurrent.ListeningExecutorService; //導入依賴的package包/類
@Before
public void setupStore() {
    InMemoryDOMDataStore operStore = new InMemoryDOMDataStore("OPER", MoreExecutors.newDirectExecutorService());
    InMemoryDOMDataStore configStore = new InMemoryDOMDataStore("CFG", MoreExecutors.newDirectExecutorService());
    schemaContext = TestModel.createTestContext();

    operStore.onGlobalContextUpdated(schemaContext);
    configStore.onGlobalContextUpdated(schemaContext);

    ImmutableMap<LogicalDatastoreType, DOMStore> stores = ImmutableMap.<LogicalDatastoreType, DOMStore> builder() //
            .put(CONFIGURATION, configStore) //
            .put(OPERATIONAL, operStore) //
            .build();

    ListeningExecutorService executor = MoreExecutors.listeningDecorator(Executors.newSingleThreadExecutor());
    domBroker = new SerializedDOMDataBroker(stores, executor);
}
 
開發者ID:hashsdn,項目名稱:hashsdn-controller,代碼行數:18,代碼來源:DOMTransactionChainTest.java

示例8: getDefaultCommitExecutor

import com.google.common.util.concurrent.ListeningExecutorService; //導入依賴的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

示例9: getS3Logs

import com.google.common.util.concurrent.ListeningExecutorService; //導入依賴的package包/類
private List<SingularityS3Log> getS3Logs(S3Configuration s3Configuration, Optional<String> group, Collection<String> prefixes) throws InterruptedException, ExecutionException, TimeoutException {
  if (prefixes.isEmpty()) {
    return Collections.emptyList();
  }

  ListeningExecutorService executorService = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(Math.min(prefixes.size(), s3Configuration.getMaxS3Threads()),
      new ThreadFactoryBuilder().setNameFormat("S3LogFetcher-%d").build()));

  try {
    List<SingularityS3Log> logs = Lists.newArrayList(getS3LogsWithExecutorService(s3Configuration, group, executorService, prefixes));
    Collections.sort(logs, LOG_COMPARATOR);
    return logs;
  } finally {
    executorService.shutdownNow();
  }
}
 
開發者ID:PacktPublishing,項目名稱:Mastering-Mesos,代碼行數:17,代碼來源:S3LogResource.java

示例10: onFinish

import com.google.common.util.concurrent.ListeningExecutorService; //導入依賴的package包/類
private void onFinish(SingularityExecutorTask task, Protos.TaskState taskState) {
  processKiller.cancelDestroyFuture(task.getTaskId());

  tasks.remove(task.getTaskId());
  processRunningTasks.remove(task.getTaskId());
  processBuildingTasks.remove(task.getTaskId());

  task.cleanup(taskState);

  ListeningExecutorService executorService = taskToShellCommandPool.remove(task.getTaskId());

  if (executorService != null) {
    executorService.shutdownNow();
    try {
      executorService.awaitTermination(5, TimeUnit.MILLISECONDS);
    } catch (InterruptedException e) {
      LOG.warn("Awaiting shutdown of shell executor service", e);
    }
  }

  logging.stopTaskLogger(task.getTaskId(), task.getLogbackLog());

  checkIdleExecutorShutdown(task.getDriver());
}
 
開發者ID:PacktPublishing,項目名稱:Mastering-Mesos,代碼行數:25,代碼來源:SingularityExecutorMonitor.java

示例11: 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);
}
 
開發者ID:PacktPublishing,項目名稱:Mastering-Mesos,代碼行數:22,代碼來源:AbstractTaskStoreTest.java

示例12: 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();
        }
    }
}
 
開發者ID:Netflix,項目名稱:metacat,代碼行數:21,代碼來源:ElasticSearchRefresh.java

示例13: exceptionArentCached_deferredFuture

import com.google.common.util.concurrent.ListeningExecutorService; //導入依賴的package包/類
@Test
public void exceptionArentCached_deferredFuture() throws Exception {
  ListeningExecutorService exec = listeningDecorator(Executors.newSingleThreadExecutor());
  try {
    executor = TestDeduplicatingExecutor.create(s -> {
      if (s == first) {
        return exec.submit(() -> {
          Thread.sleep(50);
          throw new IllegalArgumentException();
        });
      }
      return Futures.immediateFuture(s);
    });
    exceptionsArentCached();
  } finally {
    exec.shutdownNow();
  }
}
 
開發者ID:liaominghua,項目名稱:zipkin,代碼行數:19,代碼來源:DeduplicatingExecutorTest.java

示例14: buildPostCommitter

import com.google.common.util.concurrent.ListeningExecutorService; //導入依賴的package包/類
private Optional<PostCommitActions> buildPostCommitter(CommitTable.Client commitTableClient ) {

            PostCommitActions postCommitter;
            PostCommitActions syncPostCommitter = new HBaseSyncPostCommitter(hbaseOmidClientConf.getMetrics(),
                                                                             commitTableClient);
            switch(hbaseOmidClientConf.getPostCommitMode()) {
                case ASYNC:
                    ListeningExecutorService postCommitExecutor =
                            MoreExecutors.listeningDecorator(Executors.newSingleThreadExecutor(
                                    new ThreadFactoryBuilder().setNameFormat("postCommit-%d").build()));
                    postCommitter = new HBaseAsyncPostCommitter(syncPostCommitter, postCommitExecutor);
                    break;
                case SYNC:
                default:
                    postCommitter = syncPostCommitter;
                    break;
            }

            return Optional.of(postCommitter);
        }
 
開發者ID:apache,項目名稱:incubator-omid,代碼行數:21,代碼來源:HBaseTransactionManager.java

示例15: 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();
}
 
開發者ID:hartwigmedical,項目名稱:hmftools,代碼行數:30,代碼來源:FastqStats.java


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