Example usage for java.util.concurrent CountDownLatch CountDownLatch

List of usage examples for java.util.concurrent CountDownLatch CountDownLatch

Introduction

In this page you can find the example usage for java.util.concurrent CountDownLatch CountDownLatch.

Prototype

public CountDownLatch(int count) 

Source Link

Document

Constructs a CountDownLatch initialized with the given count.

Usage

From source file:org.smartfrog.services.anubis.PartitionTest.java

/**
 * Test that a partition can form two asymmetric partitions, with one
 * stabilizing, and then reform the original partition.
 *///from   w  w  w .  ja  v  a  2  s .  c  o m
public void testAsymmetricPartition() throws Exception {
    int minorPartitionSize = configs.length / 2;
    BitView A = new BitView();
    BitView B = new BitView();
    BitView All = new BitView();
    CountDownLatch latchA = new CountDownLatch(minorPartitionSize);
    List<TestNode> partitionA = new ArrayList<TestNode>();

    CountDownLatch latchB = new CountDownLatch(minorPartitionSize);
    List<TestNode> partitionB = new ArrayList<TestNode>();

    int i = 0;
    for (TestNode member : partition) {
        All.add(member.getIdentity());
        if (i++ % 2 == 0) {
            partitionA.add(member);
            member.latch = latchA;
            member.cardinality = minorPartitionSize;
            A.add(member.getIdentity());
        } else {
            partitionB.add(member);
            member.latch = latchB;
            member.cardinality = minorPartitionSize;
            B.add(member.getIdentity());
        }
    }
    log.info("asymmetric partitioning: " + A);
    controller.asymPartition(A);
    log.info("Awaiting stability of minor partition A");
    assertTrue("Partition A did not stabilize", latchA.await(60, TimeUnit.SECONDS));
    // The other partition should still be unstable.
    assertEquals(configs.length / 2, latchB.getCount());

    for (TestNode member : partitionA) {
        assertEquals(A, member.getPartition());
    }

    // reform
    CountDownLatch latch = new CountDownLatch(configs.length);
    for (TestNode node : partition) {
        node.latch = latch;
        node.cardinality = configs.length;
    }

    controller.clearPartitions();
    log.info("Awaiting stability of reformed major partition");
    assertTrue("Partition did not reform", latch.await(60, TimeUnit.SECONDS));

    for (TestNode member : partition) {
        assertEquals(All, member.getPartition());
    }
}

From source file:com.vmware.photon.controller.api.client.resource.SystemStatusRestApiTest.java

@Test
public void testGetVmAsync() throws IOException, InterruptedException {
    final SystemStatus systemStatus = new SystemStatus();
    systemStatus.setStatus(StatusType.READY);

    ObjectMapper mapper = new ObjectMapper();
    String serialized = mapper.writeValueAsString(systemStatus);

    setupMocks(serialized, HttpStatus.SC_OK);

    SystemStatusApi systemStatusApi = new SystemStatusRestApi(restClient);

    final CountDownLatch latch = new CountDownLatch(1);

    systemStatusApi.getSystemStatusAsync(new FutureCallback<SystemStatus>() {
        @Override// w  w w .jav a  2  s .c om
        public void onSuccess(@Nullable SystemStatus result) {
            assertEquals(result, systemStatus);
            latch.countDown();
        }

        @Override
        public void onFailure(Throwable t) {
            fail(t.toString());
            latch.countDown();
        }
    });

    assertThat(latch.await(COUNTDOWNLATCH_AWAIT_TIMEOUT, TimeUnit.SECONDS), is(true));
}

From source file:org.apache.cxf.systest.jaxrs.JAXRSCxfContinuationsTest.java

private void doTestContinuation(String pathSegment) throws Exception {
    ThreadPoolExecutor executor = new ThreadPoolExecutor(1, 1, 0, TimeUnit.SECONDS,
            new ArrayBlockingQueue<Runnable>(10));
    CountDownLatch startSignal = new CountDownLatch(1);
    CountDownLatch doneSignal = new CountDownLatch(1);

    executor.execute(new BookWorker("http://localhost:" + PORT + "/bookstore/" + pathSegment + "/1", "1",
            "CXF in Action1", startSignal, doneSignal));
    startSignal.countDown();/*from   ww  w  .j av a2s.co m*/
    doneSignal.await(60, TimeUnit.SECONDS);
    executor.shutdownNow();
    assertEquals("Not all invocations have completed", 0, doneSignal.getCount());
}

From source file:com.sharethis.loopy.test.NetworkStateTest.java

public void testShortenReturnsWhenNoNetwork() throws InterruptedException, IOException {

    Session.getInstance().waitForStart();

    final String url = "foobar";
    final Holder<Item> result = new Holder<Item>();
    final Holder<Throwable> resultThrowable = new Holder<Throwable>();
    final CountDownLatch latch = new CountDownLatch(1);

    HttpClientFactory httpClientFactory = Mockito.mock(HttpClientFactory.class);
    HttpClient httpClient = Mockito.mock(HttpClient.class);
    final LoopyState state = Mockito.mock(LoopyState.class);

    ApiClient client = new ApiClient() {
        @Override//from ww  w  .ja  va  2s .c om
        public LoopyState getState() {
            return state;
        }
    };

    Mockito.when(state.hasSTDID()).thenReturn(true);
    Mockito.when(state.getSTDID()).thenReturn("foobar_stdid");

    Mockito.when(httpClientFactory.getClient()).thenReturn(httpClient);
    Mockito.when(httpClient.execute((HttpPost) Mockito.any())).thenThrow(new SocketTimeoutException());

    LoopyAccess.setApiClient(client);
    LoopyAccess.setHttpClientFactory(httpClientFactory);

    Loopy.shorten(url, new ShareCallback() {
        @Override
        public void onResult(Item item, Throwable error) {
            result.set(item);
            resultThrowable.set(error);
            latch.countDown();
        }
    });

    assertTrue(latch.await(2, TimeUnit.SECONDS));

    Item after = result.get();
    Throwable error = resultThrowable.get();

    assertNotNull(after);

    // We expect an error because the network is down
    assertNotNull(error);

    assertTrue(error instanceof LoopyException);

    LoopyException le = (LoopyException) error;

    assertEquals(LoopyException.CLIENT_TIMEOUT, le.getCode());

    assertEquals(url, after.getUrl());
    assertNull(after.getShortlink());

    Mockito.verify(httpClient).execute((HttpPost) Mockito.any());
}

From source file:com.teradata.benchto.driver.jdbc.ConnectionPoolTest.java

private void openGivenConnectionsAmountSimultaneously(String dataSourceName, int connectionsCount)
        throws SQLException, InterruptedException, TimeoutException {
    ExecutorService executorService = newFixedThreadPool(connectionsCount);
    ExecutorCompletionService<?> completionService = new ExecutorCompletionService(executorService);
    CountDownLatch countDownLatch = new CountDownLatch(connectionsCount);
    DataSource dataSource = applicationContext.getBean(dataSourceName, DataSource.class);

    range(0, connectionsCount).mapToObj(i -> createQueryRunnable(dataSource, countDownLatch))
            .forEach(completionService::submit);

    try {/*from  www .  j  a  va2 s . c  om*/
        for (int i = 0; i < connectionsCount; i++) {
            try {
                Future<?> future = completionService.take();
                future.get(1, MINUTES);
            } catch (ExecutionException e) {
                rethrowException(e.getCause());
            }
        }
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
    } finally {
        executorService.shutdownNow();
        executorService.awaitTermination(1, MINUTES);
    }
}

From source file:com.alibaba.cobar.client.support.execution.DefaultConcurrentRequestProcessor.java

public List<Object> process(List<ConcurrentRequest> requests) {
    List<Object> resultList = new ArrayList<Object>();

    if (CollectionUtils.isEmpty(requests))
        return resultList;

    List<RequestDepository> requestsDepo = fetchConnectionsAndDepositForLaterUse(requests);
    final CountDownLatch latch = new CountDownLatch(requestsDepo.size());
    List<Future<Object>> futures = new ArrayList<Future<Object>>();
    try {//from  w  w  w  . jav a2s . c o  m

        for (RequestDepository rdepo : requestsDepo) {
            ConcurrentRequest request = rdepo.getOriginalRequest();
            final SqlMapClientCallback action = request.getAction();
            final Connection connection = rdepo.getConnectionToUse();

            futures.add(request.getExecutor().submit(new Callable<Object>() {
                public Object call() throws Exception {
                    try {
                        return executeWith(connection, action);
                    } finally {
                        latch.countDown();
                    }
                }
            }));
        }

        try {
            latch.await();
        } catch (InterruptedException e) {
            throw new ConcurrencyFailureException(
                    "interrupted when processing data access request in concurrency", e);
        }

    } finally {
        for (RequestDepository depo : requestsDepo) {
            Connection springCon = depo.getConnectionToUse();
            DataSource dataSource = depo.getOriginalRequest().getDataSource();
            try {
                if (springCon != null) {
                    if (depo.isTransactionAware()) {
                        springCon.close();
                    } else {
                        DataSourceUtils.doReleaseConnection(springCon, dataSource);
                    }
                }
            } catch (Throwable ex) {
                logger.info("Could not close JDBC Connection", ex);
            }
        }
    }

    fillResultListWithFutureResults(futures, resultList);

    return resultList;
}

From source file:example.springdata.mongodb.people.ReactiveMongoTemplateIntegrationTest.java

/**
 * This sample performs a count, inserts data and performs a count again using reactive operator chaining. It prints
 * the two counts ({@code 4} and {@code 6}) to the console.
 *///from www  .  ja v a  2  s .c o  m
@Test
public void shouldInsertAndCountData() throws Exception {

    CountDownLatch countDownLatch = new CountDownLatch(1);

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

    countDownLatch.await();
}

From source file:CountUpDownLatch.java

public void setCount(int count) {

    if (count == 0) {
        if (latch.getCount() != 0) {
            latch.countDown();/*from w w w . ja  va  2s .c o m*/
        }
    } else if (latch.getCount() == 0) {
        latch = new CountDownLatch(1);
    }

    this.count = count;
}

From source file:com.ibm.jaggr.core.impl.cache.GzipCacheImplTest.java

@Before
public void setup() throws IOException {
    latch1 = new CountDownLatch(1);
    latch2 = new CountDownLatch(1);
    tempdir = Files.createTempDir();
    tempfile = new File(tempdir, "source");
    deletedCacheFiles = new ArrayList<String>();
    FileWriter writer = new FileWriter(tempfile);
    writer.append(testData);//from   ww w  . jav a 2 s. c  o m
    writer.close();
    mockAggregator = EasyMock.createNiceMock(IAggregator.class);
    mockCacheManager = EasyMock.createNiceMock(ICacheManager.class);
    executors = new ExecutorsImpl(null, null, null, null);
    EasyMock.expect(mockAggregator.getCacheManager()).andReturn(mockCacheManager).anyTimes();
    EasyMock.expect(mockAggregator.getExecutors()).andAnswer(new IAnswer<IExecutors>() {
        @Override
        public IExecutors answer() throws Throwable {
            return executors;
        }
    }).anyTimes();
    EasyMock.expect(mockCacheManager.getCacheDir()).andReturn(tempdir).anyTimes();
    mockCacheManager.createCacheFileAsync(EasyMock.isA(String.class), EasyMock.isA(InputStream.class),
            EasyMock.isA(ICacheManager.CreateCompletionCallback.class));
    EasyMock.expectLastCall().andAnswer(new IAnswer<Object>() {
        @Override
        public Object answer() throws Throwable {
            final String prefix = (String) EasyMock.getCurrentArguments()[0];
            final InputStream in = (InputStream) EasyMock.getCurrentArguments()[1];
            final ICacheManager.CreateCompletionCallback callback = (ICacheManager.CreateCompletionCallback) EasyMock
                    .getCurrentArguments()[2];
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        latch1.await();
                        File cacheFile = File.createTempFile(prefix, ".cache", tempdir);
                        CopyUtil.copy(in, new FileOutputStream(cacheFile));
                        callback.completed(cacheFile.getName(), null);
                        latch2.countDown();
                    } catch (Exception ex) {
                        callback.completed(null, ex);
                    }
                }
            }).start();
            return null;
        }
    }).anyTimes();
    mockCacheManager.deleteFileDelayed(EasyMock.isA((String.class)));
    EasyMock.expectLastCall().andAnswer(new IAnswer<Object>() {
        @Override
        public Object answer() throws Throwable {
            deletedCacheFiles.add((String) EasyMock.getCurrentArguments()[0]);
            return null;
        }
    }).anyTimes();
}

From source file:com.netflix.curator.framework.recipes.locks.TestReaper.java

@Test
public void testUsingLeader() throws Exception {
    final Timing timing = new Timing();
    final CuratorFramework client = makeClient(timing, null);
    final CountDownLatch latch = new CountDownLatch(1);
    LeaderSelectorListener listener = new LeaderSelectorListener() {
        @Override//w  w w.j a  v a 2  s  .  c  om
        public void takeLeadership(CuratorFramework client) throws Exception {
            Reaper reaper = new Reaper(client, 1);
            try {
                reaper.addPath("/one/two/three", Reaper.Mode.REAP_UNTIL_DELETE);
                reaper.start();

                timing.sleepABit();
                latch.countDown();
            } finally {
                IOUtils.closeQuietly(reaper);
            }
        }

        @Override
        public void stateChanged(CuratorFramework client, ConnectionState newState) {
        }
    };
    LeaderSelector selector = new LeaderSelector(client, "/leader", listener);
    try {
        client.start();
        client.create().creatingParentsIfNeeded().forPath("/one/two/three");

        Assert.assertNotNull(client.checkExists().forPath("/one/two/three"));

        selector.start();
        timing.awaitLatch(latch);

        Assert.assertNull(client.checkExists().forPath("/one/two/three"));
    } finally {
        IOUtils.closeQuietly(selector);
        IOUtils.closeQuietly(client);
    }
}