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:com.vmware.photon.controller.api.client.resource.ProjectRestApiTest.java

@Test
public void testGetProjectAsync() throws IOException, InterruptedException {
    final Project project1 = new Project();
    project1.setId("project1");

    ObjectMapper mapper = new ObjectMapper();
    String serializedTask = mapper.writeValueAsString(project1);

    setupMocks(serializedTask, HttpStatus.SC_OK);

    ProjectApi projectApi = new ProjectRestApi(restClient);

    final CountDownLatch latch = new CountDownLatch(1);

    projectApi.getProjectAsync("foo", new FutureCallback<Project>() {
        @Override/*www.  j a va 2 s. com*/
        public void onSuccess(@Nullable Project result) {
            assertEquals(result, project1);
            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:core.service.test.executor.remote.TestRemoteServiceExecutor.java

@Test(timeout = 60000)
public void testExecute_concurrent() throws SecurityException, NoSuchMethodException, InterruptedException {
    int max = 20;
    final CountDownLatch latch = new CountDownLatch(max);

    for (int count = 0; count < max; count++) {
        new Thread() {
            public void run() {
                try {
                    RemoteServiceExecutor executor = new RemoteServiceExecutor();
                    // TODO: commented out to fix compile error
                    //                        RemoteServiceExecutor executor = new RemoteServiceExecutor(context);

                    // invoke math service
                    ServiceRequestImpl request = new ServiceRequestImpl();
                    request.setArguments(new Object[] { 2, 2 });
                    request.setParamTypes(new Class[] { Integer.class, Integer.class });
                    request.setMethodName("add");
                    request.setServiceInterfaceClassName(MathService.class.getName());
                    ServiceResult result = executor.execute(request);

                    Assert.assertTrue(result.isSuccess());
                    Assert.assertEquals(4, result.getPayload());

                    // invoke exception service
                    request = new ServiceRequestImpl();
                    request.setArguments(null);
                    request.setParamTypes(null);
                    request.setMethodName("throwException");
                    request.setServiceInterfaceClassName(ThrowExceptionService.class.getName());
                    ServiceResult exceptionResult = executor.execute(request);
                    Assert.assertTrue(exceptionResult.isException());

                    // invoke sleep service
                    request = new ServiceRequestImpl();
                    request.setArguments(new Object[] { 1000L });
                    request.setParamTypes(new Class[] { long.class });
                    request.setMethodName("sleep");
                    request.setServiceInterfaceClassName(SleepService.class.getName());
                    executor.execute(request);
                } catch (SecurityException e) {
                }// w  w w  .j av  a 2s  .co m
                synchronized (TestRemoteServiceExecutor.this) {
                    latch.countDown();
                }
            }
        }.start();
    }

    latch.await();
    logger.info("Finished remote service executor test.");
}

From source file:com.github.sdbg.core.test.util.PlainTestProject.java

/**
 * Disposes allocated resources and deletes project.
 *//*from   w  w  w  .j  a  va  2 s .  c o  m*/
public void dispose() throws Exception {
    final IWorkspace workspace = ResourcesPlugin.getWorkspace();

    final CountDownLatch latch = new CountDownLatch(1);

    try {
        workspace.run(new IWorkspaceRunnable() {
            @Override
            public void run(IProgressMonitor monitor) throws CoreException {
                TestUtilities.deleteProject(project);
                latch.countDown();
            }
        }, null);
    } finally {
        latch.countDown();
    }

    latch.await();
}

From source file:org.cleverbus.core.common.asynch.confirm.ConfirmationPollExecutorTest.java

@Test
public void testGetNextMessage_moreThreads() throws InterruptedException {
    // firstly commit messages to DB (we can commit because we have embedded DB for tests only)
    TransactionTemplate txTemplate = new TransactionTemplate(jpaTransactionManager);
    txTemplate.execute(new TransactionCallbackWithoutResult() {
        @Override/*from   w  ww  . j a va2s . c o m*/
        protected void doInTransactionWithoutResult(TransactionStatus status) {
            Message msg = insertNewMessage("1234_4567");
            confirmationService.insertFailedConfirmation(msg);

            msg = insertNewMessage("1234_4567_8");
            confirmationService.insertFailedConfirmation(msg);

            msg = insertNewMessage("1234_4567_9");
            confirmationService.insertFailedConfirmation(msg);
        }
    });

    // prepare threads
    int threads = 5;
    final CountDownLatch latch = new CountDownLatch(threads);
    Runnable task = new Runnable() {

        @Override
        public void run() {
            try {
                pollExecutor.run();
            } finally {
                latch.countDown();
            }
        }
    };

    mock.expectedMessageCount(3);

    // start processing and waits for result
    for (int i = 0; i < threads; i++) {
        new Thread(task).start();
    }

    latch.await();

    mock.assertIsSatisfied();

    // verify messages
    ExternalCall extCall1 = findConfirmation("1234_4567");
    assertThat(extCall1, notNullValue());
    assertThat(extCall1.getState(), is(ExternalCallStateEnum.PROCESSING));

    ExternalCall extCall2 = findConfirmation("1234_4567_8");
    assertThat(extCall2, notNullValue());
    assertThat(extCall2.getState(), is(ExternalCallStateEnum.PROCESSING));

    ExternalCall extCall3 = findConfirmation("1234_4567_9");
    assertThat(extCall3, notNullValue());
    assertThat(extCall3.getState(), is(ExternalCallStateEnum.PROCESSING));

    // check confirmationService
    confirmationService.confirmationFailed(extCall1);
    extCall1 = findConfirmation("1234_4567");
    assertThat(extCall1.getState(), is(ExternalCallStateEnum.FAILED));

    confirmationService.confirmationComplete(extCall2);
    extCall2 = findConfirmation("1234_4567_8");
    assertThat(extCall2.getState(), is(ExternalCallStateEnum.OK));
}

From source file:com.networknt.basic.BasicAuthHandlerTest.java

@Test
public void testWithRightCredentials() throws Exception {
    final Http2Client client = Http2Client.getInstance();
    final CountDownLatch latch = new CountDownLatch(1);
    final ClientConnection connection;
    try {/*from  w  ww  . j ava2s .co m*/
        connection = client.connect(new URI("http://localhost:17352"), Http2Client.WORKER, Http2Client.SSL,
                Http2Client.BUFFER_POOL, OptionMap.EMPTY).get();
    } catch (Exception e) {
        throw new ClientException(e);
    }
    final AtomicReference<ClientResponse> reference = new AtomicReference<>();
    try {
        ClientRequest request = new ClientRequest().setPath("/v2/pet").setMethod(Methods.GET);
        request.getRequestHeaders().put(Headers.HOST, "localhost");
        request.getRequestHeaders().put(Headers.AUTHORIZATION,
                "BASIC " + encodeCredentials("user1", "user1pass"));
        connection.sendRequest(request, client.createClientCallback(reference, latch));
        latch.await();
    } catch (Exception e) {
        logger.error("Exception: ", e);
        throw new ClientException(e);
    } finally {
        IoUtils.safeClose(connection);
    }
    int statusCode = reference.get().getResponseCode();
    Assert.assertEquals(200, statusCode);
    if (statusCode == 200) {
        Assert.assertNotNull(reference.get().getAttachment(Http2Client.RESPONSE_BODY));
    }
}

From source file:com.microsoft.office.integration.test.EventsAsyncTestCase.java

public void testUpdate() {
    prepareEvent();/*w  w  w .  j  a v  a  2s. co  m*/
    counter = new CountDownLatch(1);
    Futures.addCallback(Me.flushAsync(), new FutureCallback<Void>() {
        public void onFailure(Throwable t) {
            reportError(t);
            counter.countDown();
        }

        public void onSuccess(Void result) {
            try {
                updateAndCheck();
                removeEvent();
            } catch (Throwable t) {
                reportError(t);
            }

            counter.countDown();
        }
    });

    try {
        if (!counter.await(60000, TimeUnit.MILLISECONDS)) {
            fail("testUpdate() timed out");
        }
    } catch (InterruptedException e) {
        fail("testUpdate() has been interrupted");
    }
}

From source file:ezbake.security.persistence.impl.FileJsonRegManagerTest.java

@Test
public void testConcurrentModification() throws FileNotFoundException, InterruptedException {

    int numThreads = 10;
    final CountDownLatch latch = new CountDownLatch(numThreads);
    final String appFile = new File(folder.getRoot(), "apps.json").getAbsolutePath();
    for (int i = 0; i < numThreads; ++i) {
        new Thread(new Runnable() {
            @Override//from  w  ww. j  a va  2  s  .  c o m
            public void run() {
                Properties properties = new Properties();
                properties.setProperty(FileRegManager.REGISTRATION_FILE_PATH, appFile);
                JsonFileRegManager manager = new JsonFileRegManager(properties);
                String sid = Thread.currentThread().getName();
                int id = Integer.parseInt(sid, 10);

                // All threads register an app
                AppPersistenceModel app = new AppPersistenceModel();
                app.setId(sid);
                app.setAppName("App " + sid);
                app.setOwner("owner" + id);
                try {
                    manager.register(app);
                } catch (RegistrationException e) {
                    e.printStackTrace();
                } finally {
                    latch.countDown();
                }
            }
        }, "" + i).start();
    }
    latch.await();
    List<FileBackedRegistration> fileApps = loadJson(new File(appFile));
    Assert.assertEquals(numThreads, fileApps.size());
}

From source file:com.basho.riak.pbc.itest.ITestDataLoad.java

@Test
public void concurrentDataLoad() throws Exception {
    final int NUM_THREADS = 5;
    final int NUM_OBJECTS = 200;

    final CountDownLatch startLatch = new CountDownLatch(1);
    final CountDownLatch endLatch = new CountDownLatch(NUM_THREADS);

    final Thread[] threads = new Thread[NUM_THREADS];
    final AtomicInteger idx = new AtomicInteger(0);

    final RiakClient riak = new RiakClient(RIAK_HOST, RIAK_PORT);

    for (int i = 0; i < threads.length; i++) {
        threads[i] = new Thread(new Runnable() {

            public void run() {
                try {
                    startLatch.await();/*from  w  w  w .j  a  va 2 s  .co m*/

                    Random rnd = new Random();
                    for (int i = 0; i < NUM_OBJECTS / NUM_THREADS; i++) {
                        String key = "data-load-" + idx.getAndIncrement();
                        String value = CharsetUtils.asString(data[rnd.nextInt(NUM_VALUES)],
                                CharsetUtils.ISO_8859_1);
                        RiakObject[] objects = riak.fetch(BUCKET, key);
                        RiakObject o = null;
                        if (objects.length == 0) {
                            o = new RiakObject(BUCKET, key, value);
                        } else {
                            o = new RiakObject(objects[0].getVclock(), objects[0].getBucketBS(),
                                    objects[0].getKeyBS(), copyFromUtf8(value));
                        }

                        RiakObject result = riak.store(o, new RequestMeta().w(2).returnBody(true))[0];
                        assertEquals(o.getBucket(), result.getBucket());
                        assertEquals(o.getKey(), result.getKey());
                        assertEquals(o.getValue(), result.getValue());
                    }
                    endLatch.countDown();
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        });
        threads[i].start();
    }

    startLatch.countDown();

    endLatch.await();
}

From source file:io.syndesis.runtime.Recordings.java

static public CountDownLatch resetRecorderLatch(Object object, int count) {
    RecordingInvocationHandler ih = null;
    if (object instanceof RecordingProxy) {
        ih = ((RecordingProxy) object).getInvocationHandler$$$();
    } else {//w  w  w.j  ava 2 s.c o  m
        ih = (RecordingInvocationHandler) Proxy.getInvocationHandler(object);
    }
    CountDownLatch latch = new CountDownLatch(count);
    ih.latch = latch;
    return latch;
}

From source file:org.neo4j.ogm.integration.TransactionRequestHandlerTest.java

@Test
public void shouldBeAbleToStartMultipleConcurrentLongRunningTransactions() throws InterruptedException {

    SessionFactory sessionFactory = new SessionFactory();
    session = sessionFactory.openSession(neo4jRule.url());

    int numThreads = 100;

    ExecutorService executor = Executors.newFixedThreadPool(numThreads);
    CountDownLatch latch = new CountDownLatch(numThreads);

    for (int i = 0; i < numThreads; i++) {
        executor.submit(new TransactionStarter(latch));
    }//from   www.j  a  v  a  2  s.com
    latch.await(); // pause until the count reaches 0
    System.out.println("all threads running");
    executor.shutdownNow();
}