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


Java ExecutorCompletionService類代碼示例

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


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

示例1: testMultipleClients

import java.util.concurrent.ExecutorCompletionService; //導入依賴的package包/類
@Test
public void testMultipleClients() throws Exception {
  ExecutorService exec = Executors.newFixedThreadPool(NUM_THREADS);
  try {
    ExecutorCompletionService<Boolean> ecs =
        new ExecutorCompletionService<Boolean>(exec);
    for (int i = 0; i < NUM_THREADS; ++i)
      ecs.submit(new IdLockTestThread("client_" + i));
    for (int i = 0; i < NUM_THREADS; ++i) {
      Future<Boolean> result = ecs.take();
      assertTrue(result.get());
    }
    idLock.assertMapEmpty();
  } finally {
    exec.shutdown();
    exec.awaitTermination(5000, TimeUnit.MILLISECONDS);
  }
}
 
開發者ID:fengchen8086,項目名稱:ditb,代碼行數:19,代碼來源:TestIdLock.java

示例2: GraphBasedSaga

import java.util.concurrent.ExecutorCompletionService; //導入依賴的package包/類
public GraphBasedSaga(EventStore eventStore,
    Executor executor,
    Map<String, SagaTask> tasks,
    SagaContext sagaContext,
    SingleLeafDirectedAcyclicGraph<SagaRequest> sagaTaskGraph) {

  this.eventStore = eventStore;
  this.tasks = tasks;

  this.transactionTaskRunner = new TaskRunner(
      traveller(sagaTaskGraph, new FromRootTraversalDirection<>()),
      new TransactionTaskConsumer(
          tasks,
          sagaContext,
          new ExecutorCompletionService<>(executor)));

  this.sagaContext = sagaContext;
  this.compensationTaskRunner = new TaskRunner(
      traveller(sagaTaskGraph, new FromLeafTraversalDirection<>()),
      new CompensationTaskConsumer(tasks, sagaContext));

  currentTaskRunner = transactionTaskRunner;
}
 
開發者ID:apache,項目名稱:incubator-servicecomb-saga,代碼行數:24,代碼來源:GraphBasedSaga.java

示例3: TransferManager

import java.util.concurrent.ExecutorCompletionService; //導入依賴的package包/類
/**
 * 
 * Very transient
 * 
 * @param timeOutSeconds
 * @param numberOfThreads
 * @param outputWriter
 */
public TransferManager( Application csapApp, int timeOutSeconds, BufferedWriter outputWriter ) {

	this.csapApp = csapApp;
	
	logger.debug( "Number of workers: {}", csapApp.lifeCycleSettings().getNumberWorkerThreads() );
	this.timeOutSeconds = timeOutSeconds;

	osCommandRunner = new OsCommandRunner( timeOutSeconds, 1, "TransferMgr" );

	this.globalWriterForResults = outputWriter;
	updateProgress( "\nExecuting distribution using : " + csapApp.lifeCycleSettings().getNumberWorkerThreads() + " threads.\n\n" );

	BasicThreadFactory schedFactory = new BasicThreadFactory.Builder()
		.namingPattern( "CsapFileTransfer-%d" )
		.daemon( true )
		.priority( Thread.NORM_PRIORITY )
		.build();

	fileTransferService = Executors.newFixedThreadPool( csapApp.lifeCycleSettings().getNumberWorkerThreads(), schedFactory );

	fileTransferComplete = new ExecutorCompletionService<String>( fileTransferService );
}
 
開發者ID:csap-platform,項目名稱:csap-core,代碼行數:31,代碼來源:TransferManager.java

示例4: CsapEventClient

import java.util.concurrent.ExecutorCompletionService; //導入依賴的package包/類
public CsapEventClient( ) {

		BasicThreadFactory eventThreadFactory = new BasicThreadFactory.Builder()
			.namingPattern( "CsapEventPost-%d" )
			.daemon( true )
			.priority( Thread.NORM_PRIORITY + 1 )
			.build();

		eventPostQueue = new ArrayBlockingQueue<>( MAX_EVENT_BACKLOG );
		// Use a single thread to sequence and post
		// eventPostPool = Executors.newFixedThreadPool(1, schedFactory, queue);
		// really only needs to be 1 - adding the others for lt scenario
		eventPostPool = new ThreadPoolExecutor( 1, 1,
			30, TimeUnit.SECONDS,
			eventPostQueue, eventThreadFactory );

		eventPostCompletionService = new ExecutorCompletionService<String>(
			eventPostPool );
	}
 
開發者ID:csap-platform,項目名稱:csap-core,代碼行數:20,代碼來源:CsapEventClient.java

示例5: doTestNullKeyNoHeader

import java.util.concurrent.ExecutorCompletionService; //導入依賴的package包/類
private void doTestNullKeyNoHeader() throws Exception {
  final KafkaChannel channel = startChannel(false);
  Properties props = channel.getProducerProps();
  KafkaProducer<String, byte[]> producer = new KafkaProducer<String, byte[]>(props);

  for (int i = 0; i < 50; i++) {
    ProducerRecord<String, byte[]> data =
        new ProducerRecord<String, byte[]>(topic, null, String.valueOf(i).getBytes());
    producer.send(data).get();
  }
  ExecutorCompletionService<Void> submitterSvc = new
          ExecutorCompletionService<Void>(Executors.newCachedThreadPool());
  List<Event> events = pullEvents(channel, submitterSvc,
          50, false, false);
  wait(submitterSvc, 5);
  List<String> finals = new ArrayList<String>(50);
  for (int i = 0; i < 50; i++) {
    finals.add(i, events.get(i).getHeaders().get(KEY_HEADER));
  }
  for (int i = 0; i < 50; i++) {
    Assert.assertTrue( finals.get(i) == null);
  }
  channel.stop();
}
 
開發者ID:moueimei,項目名稱:flume-release-1.7.0,代碼行數:25,代碼來源:TestKafkaChannel.java

示例6: putEvents

import java.util.concurrent.ExecutorCompletionService; //導入依賴的package包/類
private void putEvents(final KafkaChannel channel, final List<List<Event>>
        events, ExecutorCompletionService<Void> submitterSvc) {
  for (int i = 0; i < 5; i++) {
    final int index = i;
    submitterSvc.submit(new Callable<Void>() {
      @Override
      public Void call() {
        Transaction tx = channel.getTransaction();
        tx.begin();
        List<Event> eventsToPut = events.get(index);
        for (int j = 0; j < 10; j++) {
          channel.put(eventsToPut.get(j));
        }
        try {
          tx.commit();
        } finally {
          tx.close();
        }
        return null;
      }
    });
  }
}
 
開發者ID:moueimei,項目名稱:flume-release-1.7.0,代碼行數:24,代碼來源:TestKafkaChannel.java

示例7: init

import java.util.concurrent.ExecutorCompletionService; //導入依賴的package包/類
@PostConstruct
public void init()
{
	final ThreadPoolExecutor executor = new BlockingThreadPoolExecutor(2, 2, 5, TimeUnit.MINUTES, 2,
		TimeUnit.MINUTES, new NamedThreadFactory("ThumbnailServiceExecutor"), new Callable<Boolean>()
		{
			@Override
			public Boolean call()
			{
				//Wait forever
				LOGGER.trace("Waited 2 minutes to queue a thumb job, waiting again.");
				return true;
			}
		});
	completionService = new ExecutorCompletionService<ThumbingCallableResult>(executor);

	new Thread()
	{
		@Override
		public void run()
		{
			setName("Thumb task finisher listener");
			watchCompleted();
		}
	}.start();
}
 
開發者ID:equella,項目名稱:Equella,代碼行數:27,代碼來源:ThumbingCallableTracker.java

示例8: ConcurrentTransferWorker

import java.util.concurrent.ExecutorCompletionService; //導入依賴的package包/類
public ConcurrentTransferWorker(final SessionPool source,
                                final SessionPool destination,
                                final Transfer transfer,
                                final TransferOptions options,
                                final TransferSpeedometer meter,
                                final TransferPrompt prompt,
                                final TransferErrorCallback error,
                                final ConnectionCallback connectionCallback,
                                final PasswordCallback passwordCallback,
                                final ProgressListener progressListener,
                                final StreamListener streamListener) {
    super(transfer, options, prompt, meter, error, progressListener, streamListener, connectionCallback, passwordCallback);
    this.source = source;
    this.destination = destination;
    final ThreadPool pool = ThreadPoolFactory.get("transfer",
            transfer.getSource().getTransferType() == Host.TransferType.newconnection ?
                    1 : PreferencesFactory.get().getInteger("queue.connections.limit"));
    this.completion = new ExecutorCompletionService<TransferStatus>(pool.executor());
}
 
開發者ID:iterate-ch,項目名稱:cyberduck,代碼行數:20,代碼來源:ConcurrentTransferWorker.java

示例9: submitFileBatch

import java.util.concurrent.ExecutorCompletionService; //導入依賴的package包/類
private void submitFileBatch(List<Future> futures, ExecutorCompletionService completionService,
                             final FileBatch fileBatch, final File rootDir, final WeightController controller) {
    futures.add(completionService.submit(new Callable<FileLoadContext>() {

        public FileLoadContext call() throws Exception {
            try {
                MDC.put(OtterConstants.splitPipelineLogFileKey,
                        String.valueOf(fileBatch.getIdentity().getPipelineId()));

                FileLoadAction fileLoadAction = (FileLoadAction) beanFactory.getBean("fileLoadAction",
                                                                                     FileLoadAction.class);
                return fileLoadAction.load(fileBatch, rootDir, controller);
            } finally {
                MDC.remove(OtterConstants.splitPipelineLogFileKey);
            }
        }
    }));
}
 
開發者ID:luoyaogui,項目名稱:otter-G,代碼行數:19,代碼來源:DataBatchLoader.java

示例10: submitRowBatch

import java.util.concurrent.ExecutorCompletionService; //導入依賴的package包/類
private void submitRowBatch(List<Future> futures, ExecutorCompletionService completionService,
                            final List<RowBatch> rowBatchs, final WeightController controller) {
    for (final RowBatch rowBatch : rowBatchs) {
        // 提交多個並行加載通道
        futures.add(completionService.submit(new Callable<DbLoadContext>() {

            public DbLoadContext call() throws Exception {
                try {
                    MDC.put(OtterConstants.splitPipelineLogFileKey,
                            String.valueOf(rowBatch.getIdentity().getPipelineId()));
                    // dbLoadAction是一個pool池化對象
                    DbLoadAction dbLoadAction = (DbLoadAction) beanFactory.getBean("dbLoadAction",
                                                                                   DbLoadAction.class);
                    return dbLoadAction.load(rowBatch, controller);
                } finally {
                    MDC.remove(OtterConstants.splitPipelineLogFileKey);
                }
            }
        }));
    }
}
 
開發者ID:luoyaogui,項目名稱:otter-G,代碼行數:22,代碼來源:DataBatchLoader.java

示例11: DAGIterator

import java.util.concurrent.ExecutorCompletionService; //導入依賴的package包/類
DAGIterator(DAGRequest req,
            List<RangeSplitter.RegionTask> regionTasks,
            TiSession session,
            SchemaInfer infer,
            PushDownType pushDownType) {
  super(req, regionTasks, session, infer);
  this.pushDownType = pushDownType;
  switch (pushDownType) {
    case NORMAL:
      dagService = new ExecutorCompletionService<>(session.getThreadPoolForTableScan());
      break;
    case STREAMING:
      streamingService = new ExecutorCompletionService<>(session.getThreadPoolForTableScan());
      break;
  }
  submitTasks();
}
 
開發者ID:pingcap,項目名稱:tikv-client-lib-java,代碼行數:18,代碼來源:DAGIterator.java

示例12: solveAny

import java.util.concurrent.ExecutorCompletionService; //導入依賴的package包/類
void solveAny(Executor e,
              Collection<Callable<Integer>> solvers)
    throws InterruptedException {
    CompletionService<Integer> cs
        = new ExecutorCompletionService<>(e);
    int n = solvers.size();
    List<Future<Integer>> futures = new ArrayList<>(n);
    Integer result = null;
    try {
        solvers.forEach(solver -> futures.add(cs.submit(solver)));
        for (int i = n; i > 0; i--) {
            try {
                Integer r = cs.take().get();
                if (r != null) {
                    result = r;
                    break;
                }
            } catch (ExecutionException ignore) {}
        }
    } finally {
        futures.forEach(future -> future.cancel(true));
    }

    if (result != null)
        use(result);
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:27,代碼來源:ExecutorCompletionService9Test.java

示例13: testMultipleClients

import java.util.concurrent.ExecutorCompletionService; //導入依賴的package包/類
@Test(timeout = 60000)
public void testMultipleClients() throws Exception {
  ExecutorService exec = Executors.newFixedThreadPool(NUM_THREADS);
  try {
    ExecutorCompletionService<Boolean> ecs =
        new ExecutorCompletionService<Boolean>(exec);
    for (int i = 0; i < NUM_THREADS; ++i)
      ecs.submit(new IdLockTestThread("client_" + i));
    for (int i = 0; i < NUM_THREADS; ++i) {
      Future<Boolean> result = ecs.take();
      assertTrue(result.get());
    }
    // make sure the entry pool will be cleared after GC and purge call
    int entryPoolSize = idLock.purgeAndGetEntryPoolSize();
    LOG.debug("Size of entry pool after gc and purge: " + entryPoolSize);
    assertEquals(0, entryPoolSize);
  } finally {
    exec.shutdown();
    exec.awaitTermination(5000, TimeUnit.MILLISECONDS);
  }
}
 
開發者ID:fengchen8086,項目名稱:ditb,代碼行數:22,代碼來源:TestIdReadWriteLock.java

示例14: testPoll1

import java.util.concurrent.ExecutorCompletionService; //導入依賴的package包/類
/**
 * poll returns non-null when the returned task is completed
 */
public void testPoll1()
    throws InterruptedException, ExecutionException {
    CompletionService cs = new ExecutorCompletionService(cachedThreadPool);
    assertNull(cs.poll());
    cs.submit(new StringTask());

    long startTime = System.nanoTime();
    Future f;
    while ((f = cs.poll()) == null) {
        if (millisElapsedSince(startTime) > LONG_DELAY_MS)
            fail("timed out");
        Thread.yield();
    }
    assertTrue(f.isDone());
    assertSame(TEST_STRING, f.get());
}
 
開發者ID:campolake,項目名稱:openjdk9,代碼行數:20,代碼來源:ExecutorCompletionServiceTest.java

示例15: testPoll2

import java.util.concurrent.ExecutorCompletionService; //導入依賴的package包/類
/**
 * timed poll returns non-null when the returned task is completed
 */
public void testPoll2()
    throws InterruptedException, ExecutionException {
    CompletionService cs = new ExecutorCompletionService(cachedThreadPool);
    assertNull(cs.poll());
    cs.submit(new StringTask());

    long startTime = System.nanoTime();
    Future f;
    while ((f = cs.poll(SHORT_DELAY_MS, MILLISECONDS)) == null) {
        if (millisElapsedSince(startTime) > LONG_DELAY_MS)
            fail("timed out");
        Thread.yield();
    }
    assertTrue(f.isDone());
    assertSame(TEST_STRING, f.get());
}
 
開發者ID:campolake,項目名稱:openjdk9,代碼行數:20,代碼來源:ExecutorCompletionServiceTest.java


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