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


Java CyclicBarrier.await方法代码示例

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


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

示例1: testAwait2_Interrupted_BrokenBarrier

import java.util.concurrent.CyclicBarrier; //导入方法依赖的package包/类
/**
 * An interruption in one party causes others waiting in timed await to
 * throw BrokenBarrierException
 */
public void testAwait2_Interrupted_BrokenBarrier() throws Exception {
    final CyclicBarrier c = new CyclicBarrier(3);
    final CountDownLatch pleaseInterrupt = new CountDownLatch(2);
    Thread t1 = new ThreadShouldThrow(InterruptedException.class) {
        public void realRun() throws Exception {
            pleaseInterrupt.countDown();
            c.await(LONG_DELAY_MS, MILLISECONDS);
        }};
    Thread t2 = new ThreadShouldThrow(BrokenBarrierException.class) {
        public void realRun() throws Exception {
            pleaseInterrupt.countDown();
            c.await(LONG_DELAY_MS, MILLISECONDS);
        }};

    t1.start();
    t2.start();
    await(pleaseInterrupt);
    t1.interrupt();
    awaitTermination(t1);
    awaitTermination(t2);
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:26,代码来源:CyclicBarrierTest.java

示例2: testTwoParties

import java.util.concurrent.CyclicBarrier; //导入方法依赖的package包/类
/**
 * A 2-party/thread barrier triggers after both threads invoke await
 */
public void testTwoParties() throws Exception {
    final CyclicBarrier b = new CyclicBarrier(2);
    Thread t = newStartedThread(new CheckedRunnable() {
        public void realRun() throws Exception {
            b.await();
            b.await();
            b.await();
            b.await();
        }});

    b.await();
    b.await();
    b.await();
    b.await();
    awaitTermination(t);
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:20,代码来源:CyclicBarrierTest.java

示例3: testNodeStatusUpdaterRetryAndNMShutdown

import java.util.concurrent.CyclicBarrier; //导入方法依赖的package包/类
@Test(timeout = 200000)
public void testNodeStatusUpdaterRetryAndNMShutdown()
    throws Exception {
  final long connectionWaitSecs = 1000;
  final long connectionRetryIntervalMs = 1000;
  YarnConfiguration conf = createNMConfig();
  conf.setLong(YarnConfiguration.RESOURCEMANAGER_CONNECT_MAX_WAIT_MS,
      connectionWaitSecs);
  conf.setLong(YarnConfiguration
          .RESOURCEMANAGER_CONNECT_RETRY_INTERVAL_MS,
      connectionRetryIntervalMs);
  conf.setLong(YarnConfiguration.NM_SLEEP_DELAY_BEFORE_SIGKILL_MS, 5000);
  conf.setLong(YarnConfiguration.NM_LOG_RETAIN_SECONDS, 1);
  CyclicBarrier syncBarrier = new CyclicBarrier(2);
  nm = new MyNodeManager2(syncBarrier, conf);
  nm.init(conf);
  nm.start();
  // start a container
  ContainerId cId = TestNodeManagerShutdown.createContainerId();
  FileContext localFS = FileContext.getLocalFSFileContext();
  TestNodeManagerShutdown.startContainer(nm, cId, localFS, nmLocalDir,
    new File("start_file.txt"));

  try {
    syncBarrier.await(10000, TimeUnit.MILLISECONDS);
  } catch (Exception e) {
  }
  Assert.assertFalse("Containers not cleaned up when NM stopped",
    assertionFailedInThread.get());
  Assert.assertTrue(((MyNodeManager2) nm).isStopped);
  Assert.assertTrue("calculate heartBeatCount based on" +
      " connectionWaitSecs and RetryIntervalSecs", heartBeatID == 2);
}
 
开发者ID:naver,项目名称:hadoop,代码行数:34,代码来源:TestNodeStatusUpdater.java

示例4: waitForSignal

import java.util.concurrent.CyclicBarrier; //导入方法依赖的package包/类
private void waitForSignal(CyclicBarrier cyclicBarrier) {
  try {
    cyclicBarrier.await();
  } catch (InterruptedException | BrokenBarrierException e) {
    fail(e.getMessage());
  }
}
 
开发者ID:apache,项目名称:incubator-servicecomb-saga,代码行数:8,代码来源:TimeAwareInterceptorTest.java

示例5: getId32

import java.util.concurrent.CyclicBarrier; //导入方法依赖的package包/类
@Test
public void getId32() throws Exception {

	int nThreads = 1000;
	int size = 1000;
	CyclicBarrier cyclicBarrier = new CyclicBarrier(nThreads + 1);
	StopWatch stopWatch = new StopWatch();
	ExecutorService executorService = Executors.newFixedThreadPool(nThreads);
	stopWatch.start();
	for (int i = 0; i < nThreads; i++) {
		int port = (8800 + (i % 10));
		executorService.execute(new Runnable() {
			@Override
			public void run() {
				try {
					cyclicBarrier.await();
					for (int j = 0; j < size; j++) {
						mockMvc.perform(
								get("/api/snowflake/get-id32?partnerKey=A" + port)
										.header("Content-Type", "application/json;charset=UTF-8"))
						       .andExpect(status().isOk())
						       .andExpect(jsonPath("$.code").value(0))
						       .andExpect(jsonPath("$.data.id").isNumber());
					}
					cyclicBarrier.await();
				} catch (Exception e) {
					e.printStackTrace();
				}

			}
		});
	}
	cyclicBarrier.await();
	cyclicBarrier.await();
	stopWatch.stop();
	System.out.println(stopWatch.prettyPrint());
	executorService.shutdown();
}
 
开发者ID:mm23504570,项目名称:snowflake,代码行数:39,代码来源:SnowflakeControllerTest.java

示例6: testCustomSchedule_startStop

import java.util.concurrent.CyclicBarrier; //导入方法依赖的package包/类
public void testCustomSchedule_startStop() throws Exception {
  final CyclicBarrier firstBarrier = new CyclicBarrier(2);
  final CyclicBarrier secondBarrier = new CyclicBarrier(2);
  final AtomicBoolean shouldWait = new AtomicBoolean(true);
  Runnable task = new Runnable() {
    @Override public void run() {
      try {
        if (shouldWait.get()) {
          firstBarrier.await();
          secondBarrier.await();
        }
      } catch (Exception e) {
        throw new RuntimeException(e);
      }
    }
  };
  TestCustomScheduler scheduler = new TestCustomScheduler();
  Future<?> future = scheduler.schedule(null, Executors.newScheduledThreadPool(10), task);
  firstBarrier.await();
  assertEquals(1, scheduler.scheduleCounter.get());
  secondBarrier.await();
  firstBarrier.await();
  assertEquals(2, scheduler.scheduleCounter.get());
  shouldWait.set(false);
  secondBarrier.await();
  future.cancel(false);
}
 
开发者ID:zugzug90,项目名称:guava-mock,代码行数:28,代码来源:AbstractScheduledServiceTest.java

示例7: awaitUnchecked

import java.util.concurrent.CyclicBarrier; //导入方法依赖的package包/类
@GwtIncompatible // used only in GwtIncomaptible tests
private void awaitUnchecked(CyclicBarrier barrier) {
  try {
    barrier.await();
  } catch (Exception e) {
    throw new RuntimeException(e);
  }
}
 
开发者ID:paul-hammant,项目名称:googles-monorepo-demo,代码行数:9,代码来源:TrustedListenableFutureTaskTest.java

示例8: testFailingVersionedUpdatedOnBulk

import java.util.concurrent.CyclicBarrier; //导入方法依赖的package包/类
public void testFailingVersionedUpdatedOnBulk() throws Exception {
    createIndex("test");
    index("test", "type", "1", "field", "1");
    final BulkResponse[] responses = new BulkResponse[30];
    final CyclicBarrier cyclicBarrier = new CyclicBarrier(responses.length);
    Thread[] threads = new Thread[responses.length];


    for (int i = 0; i < responses.length; i++) {
        final int threadID = i;
        threads[threadID] = new Thread(() -> {
            try {
                cyclicBarrier.await();
            } catch (Exception e) {
                return;
            }
            BulkRequestBuilder requestBuilder = client().prepareBulk();
            requestBuilder.add(client().prepareUpdate("test", "type", "1").setVersion(1)
                .setDoc(Requests.INDEX_CONTENT_TYPE, "field", threadID));
            responses[threadID] = requestBuilder.get();

        });
        threads[threadID].start();

    }

    for (int i = 0; i < threads.length; i++) {
        threads[i].join();
    }

    int successes = 0;
    for (BulkResponse response : responses) {
        if (!response.hasFailures()) {
            successes++;
        }
    }

    assertThat(successes, equalTo(1));
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:40,代码来源:BulkWithUpdatesIT.java

示例9: testNormalConcurrentJoins

import java.util.concurrent.CyclicBarrier; //导入方法依赖的package包/类
public void testNormalConcurrentJoins() throws InterruptedException {
    Thread[] threads = new Thread[3 + randomInt(5)];
    ArrayList<DiscoveryNode> nodes = new ArrayList<>();
    nodes.add(clusterService.localNode());
    final CyclicBarrier barrier = new CyclicBarrier(threads.length);
    final List<Throwable> backgroundExceptions = new CopyOnWriteArrayList<>();
    for (int i = 0; i < threads.length; i++) {
        final DiscoveryNode node = newNode(i);
        final int iterations = rarely() ? randomIntBetween(1, 4) : 1;
        nodes.add(node);
        threads[i] = new Thread(new AbstractRunnable() {
            @Override
            public void onFailure(Exception e) {
                logger.error("unexpected error in join thread", e);
                backgroundExceptions.add(e);
            }

            @Override
            protected void doRun() throws Exception {
                barrier.await();
                for (int i = 0; i < iterations; i++) {
                    logger.debug("{} joining", node);
                    joinNode(node);
                }
            }
        }, "t_" + i);
        threads[i].start();
    }

    logger.info("--> waiting for joins to complete");
    for (Thread thread : threads) {
        thread.join();
    }

    assertNodesInCurrentState(nodes);
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:37,代码来源:NodeJoinControllerTests.java

示例10: testCheckJobCompleteSuccess

import java.util.concurrent.CyclicBarrier; //导入方法依赖的package包/类
@Test(timeout=20000)
public void testCheckJobCompleteSuccess() throws Exception {
  Configuration conf = new Configuration();
  conf.set(MRJobConfig.MR_AM_STAGING_DIR, stagingDir);
  AsyncDispatcher dispatcher = new AsyncDispatcher();
  dispatcher.init(conf);
  dispatcher.start();
  CyclicBarrier syncBarrier = new CyclicBarrier(2);
  OutputCommitter committer = new TestingOutputCommitter(syncBarrier, true);
  CommitterEventHandler commitHandler =
      createCommitterEventHandler(dispatcher, committer);
  commitHandler.init(conf);
  commitHandler.start();

  JobImpl job = createRunningStubbedJob(conf, dispatcher, 2, null);
  completeJobTasks(job);
  assertJobState(job, JobStateInternal.COMMITTING);

  // let the committer complete and verify the job succeeds
  syncBarrier.await();
  assertJobState(job, JobStateInternal.SUCCEEDED);
  
  job.handle(new JobEvent(job.getID(),
      JobEventType.JOB_TASK_ATTEMPT_COMPLETED));
  assertJobState(job, JobStateInternal.SUCCEEDED);

  job.handle(new JobEvent(job.getID(), 
      JobEventType.JOB_MAP_TASK_RESCHEDULED));
  assertJobState(job, JobStateInternal.SUCCEEDED);
  
  dispatcher.stop();
  commitHandler.stop();
}
 
开发者ID:naver,项目名称:hadoop,代码行数:34,代码来源:TestJobImpl.java

示例11: testWaitForOpsToComplete

import java.util.concurrent.CyclicBarrier; //导入方法依赖的package包/类
public void testWaitForOpsToComplete() throws BrokenBarrierException, InterruptedException {
    final int seqNo = randomIntBetween(0, 32);
    final CyclicBarrier barrier = new CyclicBarrier(2);
    final AtomicBoolean complete = new AtomicBoolean();
    final Thread thread = new Thread(() -> {
        try {
            // sychronize starting with the test thread
            barrier.await();
            tracker.waitForOpsToComplete(seqNo);
            complete.set(true);
            // synchronize with the test thread checking if we are no longer waiting
            barrier.await();
        } catch (BrokenBarrierException | InterruptedException e) {
            throw new RuntimeException(e);
        }
    });

    thread.start();

    // synchronize starting with the waiting thread
    barrier.await();

    final List<Integer> elements = IntStream.rangeClosed(0, seqNo).boxed().collect(Collectors.toList());
    Randomness.shuffle(elements);
    for (int i = 0; i < elements.size() - 1; i++) {
        tracker.markSeqNoAsCompleted(elements.get(i));
        assertFalse(complete.get());
    }

    tracker.markSeqNoAsCompleted(elements.get(elements.size() - 1));
    // synchronize with the waiting thread to mark that it is complete
    barrier.await();
    assertTrue(complete.get());

    thread.join();
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:37,代码来源:LocalCheckpointTrackerTests.java

示例12: awaiter

import java.util.concurrent.CyclicBarrier; //导入方法依赖的package包/类
private static Awaiter awaiter(final CyclicBarrier barrier,
                               final long millis) {
    return new Awaiter() { public void run() {
        toTheStartingGate();

        try { barrier.await(millis, MILLISECONDS); }
        catch (Throwable result) { result(result); }}};
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:9,代码来源:Basic.java

示例13: testIsLocked

import java.util.concurrent.CyclicBarrier; //导入方法依赖的package包/类
public void testIsLocked(boolean fair) {
    final ReentrantLock lock = new ReentrantLock(fair);
    try {
        assertFalse(lock.isLocked());
        lock.lock();
        assertTrue(lock.isLocked());
        lock.lock();
        assertTrue(lock.isLocked());
        lock.unlock();
        assertTrue(lock.isLocked());
        lock.unlock();
        assertFalse(lock.isLocked());
        final CyclicBarrier barrier = new CyclicBarrier(2);
        Thread t = newStartedThread(new CheckedRunnable() {
                public void realRun() throws Exception {
                    lock.lock();
                    assertTrue(lock.isLocked());
                    barrier.await();
                    barrier.await();
                    lock.unlock();
                }});

        barrier.await();
        assertTrue(lock.isLocked());
        barrier.await();
        awaitTermination(t);
        assertFalse(lock.isLocked());
    } catch (Exception fail) { threadUnexpectedException(fail); }
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:30,代码来源:ReentrantLockTest.java

示例14: testResetWithoutBreakage

import java.util.concurrent.CyclicBarrier; //导入方法依赖的package包/类
/**
 * Reset of a non-broken barrier does not break barrier
 */
public void testResetWithoutBreakage() throws Exception {
    final CyclicBarrier barrier = new CyclicBarrier(3);
    for (int i = 0; i < 3; i++) {
        final CyclicBarrier start = new CyclicBarrier(3);
        Thread t1 = newStartedThread(new CheckedRunnable() {
            public void realRun() throws Exception {
                start.await();
                barrier.await();
            }});

        Thread t2 = newStartedThread(new CheckedRunnable() {
            public void realRun() throws Exception {
                start.await();
                barrier.await();
            }});

        start.await();
        barrier.await();
        awaitTermination(t1);
        awaitTermination(t2);
        assertFalse(barrier.isBroken());
        assertEquals(0, barrier.getNumberWaiting());
        if (i == 1) barrier.reset();
        assertFalse(barrier.isBroken());
        assertEquals(0, barrier.getNumberWaiting());
    }
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:31,代码来源:CyclicBarrierTest.java

示例15: testSingleParty

import java.util.concurrent.CyclicBarrier; //导入方法依赖的package包/类
/**
 * A 1-party barrier triggers after single await
 */
public void testSingleParty() throws Exception {
    CyclicBarrier b = new CyclicBarrier(1);
    assertEquals(1, b.getParties());
    assertEquals(0, b.getNumberWaiting());
    b.await();
    b.await();
    assertEquals(0, b.getNumberWaiting());
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:12,代码来源:CyclicBarrierTest.java


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