当前位置: 首页>>代码示例>>Java>>正文


Java CountDownLatch类代码示例

本文整理汇总了Java中java.util.concurrent.CountDownLatch的典型用法代码示例。如果您正苦于以下问题:Java CountDownLatch类的具体用法?Java CountDownLatch怎么用?Java CountDownLatch使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


CountDownLatch类属于java.util.concurrent包,在下文中一共展示了CountDownLatch类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: asyncCRUDShouldSucceed

import java.util.concurrent.CountDownLatch; //导入依赖的package包/类
@Test
public void asyncCRUDShouldSucceed() throws InterruptedException {
    CountDownLatch latch = new CountDownLatch(1);
    Somethingcomposite something = createSomething(0, 0);
    SomethingcompositeRecord somethingcompositeRecord = new SomethingcompositeRecord();
    somethingcompositeRecord.from(something);
    compositeDao.insertExecAsync(something).
            thenCompose(
                v-> compositeDao.findByIdAsync(somethingcompositeRecord.key())).
            thenCompose(fetchSomething -> {
                fetchSomething.getSomejsonobject().put("foo", "bar");
                return compositeDao.updateExecAsync(fetchSomething);
            }).
            thenCompose(v2->compositeDao.deleteExecAsync(somethingcompositeRecord.key())).
            whenComplete(failOrCountDown(latch));
    await(latch);
}
 
开发者ID:jklingsporn,项目名称:vertx-jooq-async,代码行数:18,代码来源:VertxSomethingCompositeDaoTest.java

示例2: testIsTerminated

import java.util.concurrent.CountDownLatch; //导入依赖的package包/类
/**
 * isTerminated is false before termination, true after
 */
public void testIsTerminated() throws InterruptedException {
    final ThreadPoolExecutor p =
        new ThreadPoolExecutor(1, 1,
                               LONG_DELAY_MS, MILLISECONDS,
                               new ArrayBlockingQueue<Runnable>(10));
    try (PoolCleaner cleaner = cleaner(p)) {
        final CountDownLatch threadStarted = new CountDownLatch(1);
        final CountDownLatch done = new CountDownLatch(1);
        assertFalse(p.isTerminating());
        p.execute(new CheckedRunnable() {
            public void realRun() throws InterruptedException {
                assertFalse(p.isTerminating());
                threadStarted.countDown();
                await(done);
            }});
        await(threadStarted);
        assertFalse(p.isTerminating());
        done.countDown();
        try { p.shutdown(); } catch (SecurityException ok) { return; }
        assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
        assertTrue(p.isTerminated());
        assertFalse(p.isTerminating());
    }
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:28,代码来源:ThreadPoolExecutorTest.java

示例3: testNotifyOnShutdown

import java.util.concurrent.CountDownLatch; //导入依赖的package包/类
public void testNotifyOnShutdown() throws Exception {
    final CountDownLatch latch2 = new CountDownLatch(1);

    serviceA.registerRequestHandler("foobar", StringMessageRequest::new, ThreadPool.Names.GENERIC,
        new TransportRequestHandler<StringMessageRequest>() {
            @Override
            public void messageReceived(StringMessageRequest request, TransportChannel channel) {
                try {
                    latch2.await();
                    logger.info("Stop ServiceB now");
                    serviceB.stop();
                } catch (Exception e) {
                    fail(e.getMessage());
                }
            }
        });
    TransportFuture<TransportResponse.Empty> foobar = serviceB.submitRequest(nodeA, "foobar",
        new StringMessageRequest(""), TransportRequestOptions.EMPTY, EmptyTransportResponseHandler.INSTANCE_SAME);
    latch2.countDown();
    try {
        foobar.txGet();
        fail("TransportException expected");
    } catch (TransportException ex) {

    }
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:27,代码来源:AbstractSimpleTransportTestCase.java

示例4: testNodes3

import java.util.concurrent.CountDownLatch; //导入依赖的package包/类
@Test
public void testNodes3() throws IOException, InterruptedException,
    KeeperException {

  int testIterations = 3;
  final CountDownLatch latch = new CountDownLatch(testIterations);
  final AtomicInteger failureCounter = new AtomicInteger();

  for (int i = 0; i < testIterations; i++) {
    runElectionSupportThread(latch, failureCounter);
  }

  Assert.assertEquals(0, failureCounter.get());

  if (!latch.await(10, TimeUnit.SECONDS)) {
    logger
        .info(
            "Waited for all threads to start, but timed out. We had {} failures.",
            failureCounter);
  }
}
 
开发者ID:didichuxing2,项目名称:https-github.com-apache-zookeeper,代码行数:22,代码来源:LeaderElectionSupportTest.java

示例5: testAwaitAdvanceAfterInterrupt

import java.util.concurrent.CountDownLatch; //导入依赖的package包/类
/**
 * awaitAdvance continues waiting if interrupted before waiting
 */
public void testAwaitAdvanceAfterInterrupt() {
    final Phaser phaser = new Phaser();
    assertEquals(0, phaser.register());
    final CountDownLatch pleaseArrive = new CountDownLatch(1);

    Thread t = newStartedThread(new CheckedRunnable() {
        public void realRun() {
            Thread.currentThread().interrupt();
            assertEquals(0, phaser.register());
            assertEquals(0, phaser.arrive());
            pleaseArrive.countDown();
            assertTrue(Thread.currentThread().isInterrupted());
            assertEquals(1, phaser.awaitAdvance(0));
            assertTrue(Thread.interrupted());
        }});

    await(pleaseArrive);
    assertThreadBlocks(t, Thread.State.WAITING);
    assertEquals(0, phaser.arrive());
    awaitTermination(t);

    Thread.currentThread().interrupt();
    assertEquals(1, phaser.awaitAdvance(0));
    assertTrue(Thread.interrupted());
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:29,代码来源:PhaserTest.java

示例6: shouldInsertAndCountData

import java.util.concurrent.CountDownLatch; //导入依赖的package包/类
/**
 * This sample performs a count, inserts data and performs a count again using reactive operator chaining.
 */
@Test
public void shouldInsertAndCountData() throws Exception {

	CountDownLatch countDownLatch = new CountDownLatch(1);

	repository.count() //
			.doOnNext(System.out::println) //
			.thenMany(repository.save(Flux.just(new Person("Hank", "Schrader", 43), //
					new Person("Mike", "Ehrmantraut", 62)))) //
			.last() //
			.flatMap(v -> repository.count()) //
			.doOnNext(System.out::println) //
			.doOnComplete(countDownLatch::countDown) //
			.doOnError(throwable -> countDownLatch.countDown()) //
			.subscribe();

	countDownLatch.await();
}
 
开发者ID:callistaenterprise,项目名称:spring-react-one,代码行数:22,代码来源:ReactivePersonRepositoryIntegrationTest.java

示例7: dropHeadWhenFull_dropHeadStrategy

import java.util.concurrent.CountDownLatch; //导入依赖的package包/类
@Test
public void dropHeadWhenFull_dropHeadStrategy() throws InterruptedException {
  SizeBoundedQueue queue = new SizeBoundedQueue(16, OverflowStrategy.dropHead);
  CountDownLatch countDown = new CountDownLatch(1);

  for (int i = 0; i < queue.maxSize; i++) {
    Message next = newMessage(i);
    Deferred<Object, MessageDroppedException, Integer> deferred = new DeferredObject<>();
    queue.offer(next, deferred);
    if (i == 0) {
      deferred.fail(ex -> {
        assertEquals(0, ((TestMessage)ex.dropped.get(0)).key);
        countDown.countDown();
      });
    }
  }
  Message overflow = newMessage(queue.maxSize);
  queue.offer(overflow, new DeferredObject<>());
  countDown.await();

  Object[] ids = collectKeys(queue);
  assertArrayEquals(new Object[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}, ids);
}
 
开发者ID:tramchamploo,项目名称:buffer-slayer,代码行数:24,代码来源:SizeBoundedQueueTest.java

示例8: forceFullGc

import java.util.concurrent.CountDownLatch; //导入依赖的package包/类
/** No guarantees, but effective in practice. */
private static void forceFullGc() {
    CountDownLatch finalizeDone = new CountDownLatch(1);
    WeakReference<?> ref = new WeakReference<Object>(new Object() {
        protected void finalize() { finalizeDone.countDown(); }});
    try {
        for (int i = 0; i < 10; i++) {
            System.gc();
            if (finalizeDone.await(1L, SECONDS) && ref.get() == null) {
                System.runFinalization(); // try to pick up stragglers
                return;
            }
        }
    } catch (InterruptedException unexpected) {
        throw new AssertionError("unexpected InterruptedException");
    }
    throw new AssertionError("failed to do a \"full\" gc");
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:19,代码来源:TimedAcquireLeak.java

示例9: chainedDeferred

import java.util.concurrent.CountDownLatch; //导入依赖的package包/类
@Test
public void chainedDeferred() throws InterruptedException {
  reporter = AsyncReporter.builder(new JdbcTemplateSender(underlying))
      .messageTimeout(10, TimeUnit.MILLISECONDS)
      .build();
  batchJdbcTemplate = new BatchJdbcTemplate(underlying, reporter);

  CountDownLatch countDown = new CountDownLatch(1);
  batchJdbcTemplate.update(INSERTION, new Object[]{randomString(), new Date()}).done(d -> {
    assertEquals(new Integer(1), d);
    String expected = randomString();
    batchJdbcTemplate.update(MODIFICATION, new Object[]{expected}).done(dd -> {
      assertEquals(new Integer(1), dd);
      int rowCount = batchJdbcTemplate.queryForObject(ROW_COUNT, Integer.class);
      assertEquals(1, rowCount);
      Object data = batchJdbcTemplate
          .queryForObject("SELECT data FROM test LIMIT 1", String.class);
      assertEquals(expected, data);
      countDown.countDown();
    });
  });
  countDown.await();
}
 
开发者ID:tramchamploo,项目名称:buffer-slayer,代码行数:24,代码来源:BatchJdbcTemplateTest.java

示例10: should_create_job_with_unique_job_number

import java.util.concurrent.CountDownLatch; //导入依赖的package包/类
@Test
public void should_create_job_with_unique_job_number() throws Throwable {
    // given:
    final Node flow = createRootFlow("flow-job-number", "yml/demo_flow2.yaml");
    final int numOfJob = 10;
    final CountDownLatch countDown = new CountDownLatch(numOfJob);

    // when:
    for (int i = 0; i < numOfJob; i++) {
        taskExecutor.execute(() -> {
            jobService.createFromFlowYml(flow.getPath(), JobCategory.MANUAL, null, mockUser);
            countDown.countDown();
        });
    }

    // then:
    countDown.await(30, TimeUnit.SECONDS);
    Assert.assertEquals(numOfJob, jobDao.numOfJob(flow.getPath()).intValue());
}
 
开发者ID:FlowCI,项目名称:flow-platform,代码行数:20,代码来源:JobServiceTest.java

示例11: testRunnableRunsAtMostOnceAfterCancellation

import java.util.concurrent.CountDownLatch; //导入依赖的package包/类
public void testRunnableRunsAtMostOnceAfterCancellation() throws Exception {
    final int iterations = scaledRandomIntBetween(1, 12);
    final AtomicInteger counter = new AtomicInteger();
    final CountDownLatch doneLatch = new CountDownLatch(iterations);
    final Runnable countingRunnable = () -> {
        counter.incrementAndGet();
        doneLatch.countDown();
    };

    final Cancellable cancellable = threadPool.scheduleWithFixedDelay(countingRunnable, TimeValue.timeValueMillis(10L), Names.GENERIC);
    doneLatch.await();
    cancellable.cancel();
    final int counterValue = counter.get();
    assertThat(counterValue, isOneOf(iterations, iterations + 1));

    if (rarely()) {
        awaitBusy(() -> {
            final int value = counter.get();
            return value == iterations || value == iterations + 1;
        }, 50L, TimeUnit.MILLISECONDS);
    }
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:23,代码来源:ScheduleWithFixedDelayTests.java

示例12: start

import java.util.concurrent.CountDownLatch; //导入依赖的package包/类
@BeforeAll
public static void start() {
  port = getFreePort();

  httpDataProvider = mock(HttpDataProvider.class);
  logger.info("Starting embedded HTTP server on port: {}", port);
  vertx = Vertx.vertx();
  DeploymentOptions options =
      new DeploymentOptions().setConfig(new JsonObject().put("http.port", port)).setInstances(1);

  CountDownLatch latch = new CountDownLatch(1);
  vertx.deployVerticle(
      new HttpServerSimulatorVerticle(httpDataProvider),
      options,
      result -> {
        logger.info("Started embedded HTTP server with result: {}", result);
        latch.countDown();
      });

  try {
    latch.await();
  } catch (InterruptedException e) {
    logger.warn("Failed to wait for the embedded HTTP server to start!");
  }
}
 
开发者ID:glytching,项目名称:dragoman,代码行数:26,代码来源:AbstractHttpTestCase.java

示例13: testRacingRegistrations

import java.util.concurrent.CountDownLatch; //导入依赖的package包/类
@Test
public void testRacingRegistrations() throws InterruptedException {
    for (int i = 0; i < ITERATIONS; i++) {
        startLatch = new CountDownLatch(THREAD_COUNT);
        registeredLatch = new CountDownLatch(THREAD_COUNT);
        canUnregisterLatch = new CountDownLatch(1);
        unregisteredLatch = new CountDownLatch(THREAD_COUNT);
        
        List<SubscriberThread> threads = startThreads();
        registeredLatch.await();
        eventBus.post("42");
        canUnregisterLatch.countDown();
        for (int t = 0; t < THREAD_COUNT; t++) {
            int eventCount = threads.get(t).eventCount;
            if (eventCount != 1) {
                fail("Failed in iteration " + i + ": thread #" + t + " has event count of " + eventCount);
            }
        }
        // Wait for threads to be done
        unregisteredLatch.await();
    }
}
 
开发者ID:weiwenqiang,项目名称:GitHub,代码行数:23,代码来源:EventBusRegistrationRacingTest.java

示例14: getFactory

import java.util.concurrent.CountDownLatch; //导入依赖的package包/类
public static JobFactory<?> getFactory(
  JobSubmitter submitter, Path scratch, int numJobs, Configuration conf,
  CountDownLatch startFlag, UserResolver resolver) throws IOException {
  GridmixJobSubmissionPolicy policy = GridmixJobSubmissionPolicy.getPolicy(
    conf, GridmixJobSubmissionPolicy.STRESS);
  if (policy == GridmixJobSubmissionPolicy.REPLAY) {
    return new DebugReplayJobFactory(
      submitter, scratch, numJobs, conf, startFlag, resolver);
  } else if (policy == GridmixJobSubmissionPolicy.STRESS) {
    return new DebugStressJobFactory(
      submitter, scratch, numJobs, conf, startFlag, resolver);
  } else if (policy == GridmixJobSubmissionPolicy.SERIAL) {
    return new DebugSerialJobFactory(
      submitter, scratch, numJobs, conf, startFlag, resolver);

  }
  return null;
}
 
开发者ID:naver,项目名称:hadoop,代码行数:19,代码来源:DebugJobFactory.java

示例15: testPhantomRead

import java.util.concurrent.CountDownLatch; //导入依赖的package包/类
@Test
public void testPhantomRead() throws Exception {
	logger.info("start phantom read");
	queryReadAccount.setFirstWaitTime(0);
	queryReadAccount.setSecondWaitTime(2000);
	queryWriteAccount.setAccountNumber(953);
	queryWriteAccount.setAmount(456.77);
	queryWriteAccount.setWaitTime(1000);
	latch = new CountDownLatch(1);
	defaultExecutor.submit(queryWriteAccount);
	defaultExecutor.submit(queryReadAccount);
	latch.await(3000, MILLISECONDS);
	assertEquals("the transaction B add a new account", 456.77, queryWriteAccount.getResult(), 0.0);
	assertEquals("the first query in the transaction A before the transaction ends", 8,
			queryReadAccount.getFirstResult());
	assertEquals("the second query in the transaction A after the transaction ends", 9,
			queryReadAccount.getSecondResult());
}
 
开发者ID:PacktPublishing,项目名称:Mastering-Java-EE-Development-with-WildFly,代码行数:19,代码来源:ReadCommittedTestCase.java


注:本文中的java.util.concurrent.CountDownLatch类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。