本文整理汇总了Java中java.util.concurrent.CountDownLatch.getCount方法的典型用法代码示例。如果您正苦于以下问题:Java CountDownLatch.getCount方法的具体用法?Java CountDownLatch.getCount怎么用?Java CountDownLatch.getCount使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类java.util.concurrent.CountDownLatch
的用法示例。
在下文中一共展示了CountDownLatch.getCount方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: testDoRetry_subscribe
import java.util.concurrent.CountDownLatch; //导入方法依赖的package包/类
@Test
public void testDoRetry_subscribe() throws Exception {
final CountDownLatch latch = new CountDownLatch(1);//全部共调用4次。成功才会减1. subscribe的失败尝试不会在做了
registry = new MockRegistry(registryUrl, latch);
registry.setBad(true);
registry.register(serviceUrl);
registry.setBad(false);
for (int i = 0; i < trytimes; i++) {
System.out.println("failback registry retry ,times:" + i);
if (latch.getCount() == 0)
break;
Thread.sleep(sleeptime);
}
assertEquals(0, latch.getCount());
}
示例2: preGetOp
import java.util.concurrent.CountDownLatch; //导入方法依赖的package包/类
@Override
public void preGetOp(final ObserverContext<RegionCoprocessorEnvironment> e,
final Get get, final List<Cell> results) throws IOException {
if (e.getEnvironment().getRegion().getRegionInfo().getReplicaId() == 0) {
CountDownLatch latch = cdl.get();
try {
if (sleepTime.get() > 0) {
LOG.info("Sleeping for " + sleepTime.get() + " ms");
Thread.sleep(sleepTime.get());
} else if (latch.getCount() > 0) {
LOG.info("Waiting for the counterCountDownLatch");
latch.await(2, TimeUnit.MINUTES); // To help the tests to finish.
if (latch.getCount() > 0) {
throw new RuntimeException("Can't wait more");
}
}
} catch (InterruptedException e1) {
LOG.error(e1);
}
} else {
LOG.info("We're not the primary replicas.");
}
}
示例3: test1
import java.util.concurrent.CountDownLatch; //导入方法依赖的package包/类
@Test
public void test1() throws InterruptedException {
setupPeers();
// A == b10, B == genesis
final CountDownLatch semaphore = new CountDownLatch(1);
ethereumB.addListener(new EthereumListenerAdapter() {
@Override
public void onBlock(Block block, List<TransactionReceipt> receipts) {
if (block.isEqual(b10)) {
semaphore.countDown();
}
}
});
semaphore.await(40, SECONDS);
// check if B == b10
if(semaphore.getCount() > 0) {
fail("PeerB bestBlock is incorrect");
}
}
示例4: triggerAndWaitForThreads
import java.util.concurrent.CountDownLatch; //导入方法依赖的package包/类
private long triggerAndWaitForThreads(List<PosterThread> threads, CountDownLatch latch) throws InterruptedException {
while (latch.getCount() != 1) {
// Let all other threads prepare and ensure this one is the last
Thread.sleep(1);
}
long start = System.currentTimeMillis();
latch.countDown();
for (PosterThread thread : threads) {
thread.join();
}
return System.currentTimeMillis() - start;
}
示例5: main
import java.util.concurrent.CountDownLatch; //导入方法依赖的package包/类
public static void main(String[] args) throws Throwable {
final String[] algorithmNames = {
"PBKDF2WITHHMACSHA1",
"PBEWITHMD5ANDDES",
"DSA",
"SHA384WITHRSA",
"RSA",
"SHA1WITHDSA",
"SHA512WITHRSA",
"MD2WITHRSA",
"PBEWITHSHA1ANDDESEDE",
"SHA1WITHRSA",
"DIFFIEHELLMAN",
"MD5WITHRSA",
"PBEWITHSHA1ANDRC2_40",
"SHA256WITHRSA",
};
final int THREADS = 2;
final ExecutorService pool = Executors.newFixedThreadPool(THREADS);
final CountDownLatch startingGate = new CountDownLatch(THREADS);
final Runnable r = new Runnable() { public void run() {
startingGate.countDown();
do {} while (startingGate.getCount() > 0);
try {
for (String algorithmName : algorithmNames)
AlgorithmId.get(algorithmName);
} catch (Throwable fail) {
throw new AssertionError(fail);
}
}};
final ArrayList<Future<?>> futures = new ArrayList<>();
for (int i = 0; i < THREADS; i++)
futures.add(pool.submit(r));
pool.shutdown();
for (Future<?> future : futures) future.get();
}
示例6: run
import java.util.concurrent.CountDownLatch; //导入方法依赖的package包/类
@Override
public void run()
{
try {
while ( !handler.allFinished() )
{
if (failure) throw new RuntimeException("FAILURE DETECTED!");
List<Thread> thrds = new LinkedList<Thread>();
for ( TeamedAgentId id : localWorldViews.keySet() )
{
if ( handler.cyclesToRun(id) >= 0)
{
thrds.add( new EventGenerator(eventsPerCycle, currentTime, localWorldViews.get(id), checkers.get(id) ) );
}
}
latch2 = new CountDownLatch(thrds.size());
for (Thread t : thrds)
{
t.start();
}
latch2.await(GLOBAL_TIMEOUT_IN_MINUTES, TimeUnit.MINUTES);
if (latch2.getCount() > 0 || failure) {
throw new RuntimeException("FAILURE DETECTED!");
}
++currentTime;
sleep(sleepTime);
}
} catch (Exception e) {
e.printStackTrace();
failure = true;
totalCountDown();
return;
}
latch.countDown();
}
示例7: stop
import java.util.concurrent.CountDownLatch; //导入方法依赖的package包/类
public void stop() {
if (this.members.isEmpty()) {
return;
}
if (logger.isInfoEnabled()) {
logger.info("Stopping beans in phase " + this.phase);
}
Collections.sort(this.members, Collections.reverseOrder());
CountDownLatch latch = new CountDownLatch(this.smartMemberCount);
Set<String> countDownBeanNames = Collections.synchronizedSet(new LinkedHashSet<String>());
for (LifecycleGroupMember member : this.members) {
if (this.lifecycleBeans.containsKey(member.name)) {
doStop(this.lifecycleBeans, member.name, latch, countDownBeanNames);
}
else if (member.bean instanceof SmartLifecycle) {
// already removed, must have been a dependent
latch.countDown();
}
}
try {
latch.await(this.timeout, TimeUnit.MILLISECONDS);
if (latch.getCount() > 0 && !countDownBeanNames.isEmpty() && logger.isWarnEnabled()) {
logger.warn("Failed to shut down " + countDownBeanNames.size() + " bean" +
(countDownBeanNames.size() > 1 ? "s" : "") + " with phase value " +
this.phase + " within timeout of " + this.timeout + ": " + countDownBeanNames);
}
}
catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
示例8: testDoRetry
import java.util.concurrent.CountDownLatch; //导入方法依赖的package包/类
/**
* Test method for
* {@link com.alibaba.dubbo.registry.internal.FailbackRegistry#doRetry()}.
*
* @throws Exception
*/
@Test
public void testDoRetry() throws Exception {
final AtomicReference<Boolean> notified = new AtomicReference<Boolean>(false);
final CountDownLatch latch = new CountDownLatch(3);//全部共调用3次。成功才会减1. subscribe register的失败尝试不会在做了
NotifyListener listner = new NotifyListener() {
public void notify(List<URL> urls) {
notified.set(Boolean.TRUE);
}
};
registry = new MockRegistry(registryUrl, latch);
registry.setBad(true);
registry.register(serviceUrl);
registry.unregister(serviceUrl);
registry.subscribe(serviceUrl.setProtocol(Constants.CONSUMER_PROTOCOL).addParameters(CollectionUtils.toStringMap("check", "false")), listner);
registry.unsubscribe(serviceUrl.setProtocol(Constants.CONSUMER_PROTOCOL).addParameters(CollectionUtils.toStringMap("check", "false")), listner);
//失败的情况不能调用到listener.
assertEquals(false, notified.get());
assertEquals(3, latch.getCount());
registry.setBad(false);
for (int i = 0; i < trytimes; i++) {
System.out.println("failback registry retry ,times:" + i);
//System.out.println(latch.getCount());
if (latch.getCount() == 0)
break;
Thread.sleep(sleeptime);
}
// Thread.sleep(100000);//for debug
assertEquals(0, latch.getCount());
//unsubscribe时会清除failedsubcribe对应key
assertEquals(false, notified.get());
}
示例9: test2
import java.util.concurrent.CountDownLatch; //导入方法依赖的package包/类
@Test
public void test2() throws InterruptedException {
SysPropConfigA.eth62 = new Eth62() {
@Override
protected void processGetBlockBodies(GetBlockBodiesMessage msg) {
List<byte[]> bodies = Arrays.asList(
mainB1B10.get(0).getEncodedBody()
);
BlockBodiesMessage response = new BlockBodiesMessage(bodies);
sendMessage(response);
}
};
setupPeers();
// A == b10, B == genesis
final CountDownLatch semaphoreDisconnect = new CountDownLatch(1);
ethereumA.addListener(new EthereumListenerAdapter() {
@Override
public void onRecvMessage(Channel channel, Message message) {
if (message instanceof DisconnectMessage) {
semaphoreDisconnect.countDown();
}
}
});
semaphoreDisconnect.await(10, SECONDS);
// check if peer was dropped
if(semaphoreDisconnect.getCount() > 0) {
fail("PeerA is not dropped");
}
}
示例10: testDoRetry_register
import java.util.concurrent.CountDownLatch; //导入方法依赖的package包/类
@Test
public void testDoRetry_register() throws Exception {
final AtomicReference<Boolean> notified = new AtomicReference<Boolean>(false);
final CountDownLatch latch = new CountDownLatch(1);//全部共调用4次。成功才会减1. subscribe的失败尝试不会在做了
NotifyListener listner = new NotifyListener() {
public void notify(List<URL> urls) {
notified.set(Boolean.TRUE);
}
};
registry = new MockRegistry(registryUrl, latch);
registry.setBad(true);
registry.subscribe(serviceUrl.setProtocol(Constants.CONSUMER_PROTOCOL).addParameters(CollectionUtils.toStringMap("check", "false")), listner);
//失败的情况不能调用到listener.
assertEquals(false, notified.get());
assertEquals(1, latch.getCount());
registry.setBad(false);
for (int i = 0; i < trytimes; i++) {
System.out.println("failback registry retry ,times:" + i);
//System.out.println(latch.getCount());
if (latch.getCount() == 0)
break;
Thread.sleep(sleeptime);
}
// Thread.sleep(100000);
assertEquals(0, latch.getCount());
//unsubscribe时会清除failedsubcribe对应key
assertEquals(true, notified.get());
}
示例11: executeThenAdd_singleThreaded
import java.util.concurrent.CountDownLatch; //导入方法依赖的package包/类
@Benchmark int executeThenAdd_singleThreaded(int reps) {
int returnValue = 0;
for (int i = 0; i < reps; i++) {
list = impl.newExecutionList();
list.execute();
listenerLatch = new CountDownLatch(numListeners);
for (int j = 0; j < numListeners; j++) {
list.add(listener, directExecutor());
returnValue += listenerLatch.getCount();
}
returnValue += listenerLatch.getCount();
}
return returnValue;
}
示例12: testDoRetry
import java.util.concurrent.CountDownLatch; //导入方法依赖的package包/类
/**
* Test method for
* {@link com.alibaba.dubbo.registry.internal.FailbackRegistry#doRetry()}.
*
* @throws Exception
*/
@Test
public void testDoRetry() throws Exception {
final AtomicReference<Boolean> notified = new AtomicReference<Boolean>(false);
final CountDownLatch latch = new CountDownLatch(3);//全部共调用3次。成功才会减1. subscribe register的失败尝试不会在做了
NotifyListener listner = new NotifyListener() {
public void notify(List<URL> urls) {
notified.set(Boolean.TRUE);
}
};
registry = new MockRegistry(registryUrl, latch);
registry.setBad(true);
registry.register(serviceUrl);
registry.unregister(serviceUrl);
registry.subscribe(serviceUrl.setProtocol(Constants.CONSUMER_PROTOCOL).addParameters(CollectionUtils.toStringMap("check", "false")), listner);
registry.unsubscribe(serviceUrl.setProtocol(Constants.CONSUMER_PROTOCOL).addParameters(CollectionUtils.toStringMap("check", "false")), listner);
//失败的情况不能调用到listener.
assertEquals(false, notified.get());
assertEquals(3, latch.getCount());
registry.setBad(false);
for (int i = 0; i < trytimes; i++) {
System.out.println("failback registry retry ,times:" + i);
//System.out.println(latch.getCount());
if (latch.getCount() == 0)
break;
Thread.sleep(sleeptime);
}
// Thread.sleep(100000);//for debug
assertEquals(0, latch.getCount());
//unsubscribe时会清除failedsubcribe对应key
assertEquals(false, notified.get());
}
示例13: test2
import java.util.concurrent.CountDownLatch; //导入方法依赖的package包/类
@Test
public void test2() throws InterruptedException {
setupPeers();
// A == B == genesis
Blockchain blockchainA = (Blockchain) ethereumA.getBlockchain();
for (Block b : forkB1B5B8_) {
blockchainA.tryToConnect(b);
}
// A == b8', B == genesis
final CountDownLatch semaphore = new CountDownLatch(1);
ethereumB.addListener(new EthereumListenerAdapter() {
@Override
public void onBlock(Block block, List<TransactionReceipt> receipts) {
if (block.isEqual(b8_)) {
semaphore.countDown();
}
}
});
ethA.sendNewBlock(b8_);
semaphore.await(10, SECONDS);
// check if B == b8'
if(semaphore.getCount() > 0) {
fail("PeerB bestBlock is incorrect");
}
}
示例14: initCluster
import java.util.concurrent.CountDownLatch; //导入方法依赖的package包/类
protected void initCluster() {
long instanceId = EstTime.currentTimeMillis();
hstore_site.setInstanceId(instanceId);
InitializeRequest request = InitializeRequest.newBuilder()
.setSenderSite(0)
.setInstanceId(instanceId)
.build();
final CountDownLatch latch = new CountDownLatch(this.num_sites-1);
RpcCallback<InitializeResponse> callback = new RpcCallback<InitializeResponse>() {
@Override
public void run(InitializeResponse parameter) {
if (debug.val) LOG.debug(String.format("Initialization Response: %s / %s",
HStoreThreadManager.formatSiteName(parameter.getSenderSite()),
parameter.getStatus()));
latch.countDown();
}
};
for (int site_id = 0; site_id < this.num_sites; site_id++) {
if (site_id == this.local_site_id) continue;
ProtoRpcController controller = new ProtoRpcController();
this.channels[site_id].initialize(controller, request, callback);
} // FOR
if (latch.getCount() > 0) {
if (debug.val)
LOG.debug(String.format("Waiting for %s initialization responses", latch.getCount()));
boolean finished = false;
try {
finished = latch.await(10, TimeUnit.SECONDS);
} catch (InterruptedException ex) {
throw new ServerFaultException("Unexpected interruption", ex);
}
assert(finished);
}
}
示例15: testPdfToTextConversions
import java.util.concurrent.CountDownLatch; //导入方法依赖的package包/类
/**
* Added to test a single transform that appeared to have problems.
* Commented out once issue was fixed, but left in the code to help with
* future issues.
* @throws Exception
*/
public void testPdfToTextConversions() throws Exception
{
final String sourceMimetype = MimetypeMap.MIMETYPE_PDF;
final String targetMimetype = MimetypeMap.MIMETYPE_TEXT_PLAIN;
int transforms = 100;
final String filename = "svn-book.pdf";
final CountDownLatch doneSignal = new CountDownLatch(transforms);
int threadCount = 8;
final ExecutorService threadPool = Executors.newFixedThreadPool(threadCount);
long time = System.currentTimeMillis();
for (int i=0; i<transforms; i++)
{
threadPool.submit(new Runnable() {
public void run()
{
try
{
pdfToTextTransform(filename, sourceMimetype, targetMimetype);
doneSignal.countDown();
}
catch (IOException e)
{
threadPool.shutdown();
e.printStackTrace();
}
}});
if (i < threadCount)
{
Thread.sleep(1000);
}
}
boolean okay = doneSignal.await(100, TimeUnit.SECONDS);
time = System.currentTimeMillis() - time;
transforms = transforms - (int)doneSignal.getCount();
String message = "Total time "+time+" ms "+(transforms > 0 ? "average="+(time/transforms)+" ms" : "")+" threads="+threadCount+" transforms="+transforms;
System.out.println(message);
if (!okay)
{
// Before the changes to PDFBox, this would fail having only done about 50 transforms.
// After the change, this takes about 55 seconds
fail("********** Transforms did not finish ********** "+message);
}
}