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.jivesoftware.os.rcvs.api.keys.SymetricalHashableKeyTest.java

License:asdf

@Test
public void testThreadSafe() throws Exception {
    System.out.println("testThreadSafe");
    final SymetricalHashableKey instance = new SymetricalHashableKey("asdfghjk");
    int poolSize = 4;
    ExecutorService threadPool = Executors.newFixedThreadPool(poolSize);
    final CountDownLatch latch = new CountDownLatch(poolSize);
    final MutableBoolean failed = new MutableBoolean(false);
    for (int i = 0; i < poolSize; i++) {
        threadPool.submit(new Runnable() {
            @Override/* w w  w .j a  v  a  2 s .  c om*/
            public void run() {
                try {
                    int count = 1000000;
                    for (long i = 0; i < count; i++) {
                        long a = Math.abs(rand.nextLong());
                        byte[] hash = instance.toHash(longBytes(a));
                        byte[] output = instance.toBytes(hash);
                        long b = bytesLong(output);
                        if (a != b) {
                            System.out.println("Failed a:" + a + " ne b:" + b);
                            failed.setValue(true);
                            return;
                        }
                    }
                } catch (InvalidKeyException | ShortBufferException | IllegalBlockSizeException
                        | BadPaddingException | ExecutionException x) {
                    failed.setValue(true);
                } finally {
                    latch.countDown();
                }
            }
        });
    }

    latch.await();
    Assert.assertFalse(failed.booleanValue());
}

From source file:com.vmware.photon.controller.nsxclient.apis.DhcpServiceApiTest.java

@Test
public void testCreateDhcpRelayProfile() throws IOException, InterruptedException {
    final DhcpRelayProfile mockResponse = new DhcpRelayProfile();
    mockResponse.setId("id");
    mockResponse.setResourceType(ServiceProfileResourceType.DHCP_RELAY_PROFILE);
    setupMocks(objectMapper.writeValueAsString(mockResponse), HttpStatus.SC_CREATED);

    DhcpServiceApi client = new DhcpServiceApi(restClient);
    final CountDownLatch latch = new CountDownLatch(1);
    client.createDhcpRelayProfile(new DhcpRelayProfileCreateSpec(),
            new com.google.common.util.concurrent.FutureCallback<DhcpRelayProfile>() {
                @Override//from   w w w.ja v  a  2s.  c  o m
                public void onSuccess(DhcpRelayProfile result) {
                    assertEquals(result, mockResponse);
                    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:kidozen.client.crash.HttpSender.java

@Override
public void send(CrashReportData report) throws ReportSenderException {
    try {//w  w  w. j a v a2 s.  c  om
        final CountDownLatch cdl = new CountDownLatch(1);
        IdentityManager.getInstance().GetRawToken(mApplicationKey, new ServiceEventListener() {
            @Override
            public void onFinish(ServiceEvent e) {
                mEvent = e;
                cdl.countDown();
            }
        });
        cdl.await(DEFAULT_TIMEOUT, TimeUnit.MINUTES);
        if (mEvent.Exception != null || mEvent.StatusCode >= HttpStatus.SC_BAD_REQUEST)
            throw new ReportSenderException(mEvent.Body);
        mToken = ((KidoZenUser) mEvent.Response).Token;

        String authHeaderValue = String.format("WRAP access_token=\"%s\"", mToken);

        Log.d(LOG_TAG, String.format("About to send log to Log V3 service: %s ", mCrashEndpoint));
        JSONObject reportAsJson = report.toJSON();

        String bc = new JSONArray(mBreadCrumbs).toString();
        reportAsJson.put(APPLICATION_BREADCRUMB, bc);

        Hashtable<String, String> headers = new Hashtable<String, String>();
        headers.put(Constants.AUTHORIZATION_HEADER, authHeaderValue);
        headers.put(Constants.CONTENT_TYPE, Constants.APPLICATION_JSON);
        headers.put(Constants.ACCEPT, Constants.APPLICATION_JSON);

        mSniManager = new SNIConnectionManager(mCrashEndpoint, reportAsJson.toString(), headers, null, true);
        Hashtable<String, String> response = mSniManager.ExecuteHttp(KZHttpMethod.POST);
        String body = response.get("responseBody");
        Integer statusCode = Integer.parseInt(response.get("statusCode"));
        if (statusCode >= HttpStatus.SC_MULTIPLE_CHOICES) {
            String exceptionMessage = (body != null ? body : "Unexpected HTTP Status Code: " + statusCode);
            throw new Exception(exceptionMessage);
        }
    } catch (InterruptedException e) {
        throw new ReportSenderException("Timeout trying to send report to KidoZen services.", e);
    } catch (ReportSenderException e) {
        throw e;
    } catch (Exception e) {
        throw new ReportSenderException("Error while sending  report to KidoZen services.", e);
    }
}

From source file:azkaban.jobExecutor.utils.process.AzkabanProcess.java

public AzkabanProcess(final List<String> cmd, final Map<String, String> env, final String workingDir,
        final Logger logger) {
    this.cmd = cmd;
    this.env = env;
    this.workingDir = workingDir;
    this.processId = -1;
    this.startupLatch = new CountDownLatch(1);
    this.completeLatch = new CountDownLatch(1);
    this.logger = logger;
}

From source file:org.apache.servicemix.jbi.cluster.engine.ClusterEndpointLoadTest.java

public void testLoadInOnly() throws Exception {
    createRoute(Transacted.Jms, true, false, true);

    final int nbThreads = 10;
    final int nbExchanges = 10;
    final ReadWriteLock lock = new ReentrantReadWriteLock();
    final CountDownLatch latch = new CountDownLatch(nbThreads);
    final AtomicInteger id = new AtomicInteger();
    lock.writeLock().lock();// w  w  w  . j  ava2  s. c  om
    for (int i = 0; i < nbThreads; i++) {
        new Thread() {
            public void run() {
                Channel client = null;
                try {
                    client = nmr1.createChannel();
                    lock.readLock().lock();
                    for (int i = 0; i < nbExchanges; i++) {
                        Exchange exchange = client.createExchange(Pattern.InOnly);
                        exchange.getIn()
                                .setBody(new StringSource("<hello id='" + id.getAndIncrement() + "'/>"));
                        exchange.setTarget(nmr1.getEndpointRegistry()
                                .lookup(ServiceHelper.createMap(Endpoint.NAME, PROXY_ENDPOINT_NAME)));
                        client.sendSync(exchange);
                        assertEquals(Status.Done, exchange.getStatus());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    lock.readLock().unlock();
                    latch.countDown();
                    if (client != null) {
                        client.close();
                    }
                }
            }
        }.start();
    }

    long t0, t1;

    t0 = System.currentTimeMillis();
    lock.writeLock().unlock();

    latch.await();

    receiver.assertExchangesReceived(nbThreads * nbExchanges, TIMEOUT);

    t1 = System.currentTimeMillis();

    System.err.println("Elapsed time: " + (t1 - t0) + " ms");
    System.err.println("Throuput: " + (nbThreads * nbExchanges * 1000 / (t1 - t0)) + " messages/sec");
}

From source file:com.liferay.mobile.android.async.FileDownloadAsyncTest.java

@Test
public void download() throws Exception {
    BasicAuthentication basic = (BasicAuthentication) session.getAuthentication();

    DigestAuthentication digest = new DigestAuthentication(basic.getUsername(), basic.getPassword());

    session.setAuthentication(digest);//from w w w.  j  ava2s  .  c  o  m

    String url = session.getServer() + "/webdav/guest/document_library/"
            + _file.getString(DLAppServiceTest.TITLE);

    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    final CountDownLatch lock = new CountDownLatch(1);

    FileProgressCallback fileProgressCallback = new FileProgressCallback() {

        @Override
        public void onBytes(byte[] bytes) {
            try {
                baos.write(bytes);
            } catch (IOException ioe) {
                fail(ioe.getMessage());
            }
        }

        @Override
        public void onProgress(int totalBytes) {
            if (totalBytes == 5) {
                try {
                    baos.flush();
                } catch (IOException ioe) {
                    fail(ioe.getMessage());
                }
            }
        }

    };

    session.setCallback(new Callback() {

        @Override
        public void inBackground(Response response) {
            assertEquals(Status.OK, response.getStatusCode());
            lock.countDown();
        }

        @Override
        public void doFailure(Exception exception) {
            fail(exception.getMessage());
            lock.countDown();
        }

    });

    HttpUtil.download(session, url, fileProgressCallback);
    lock.await(500, TimeUnit.MILLISECONDS);
    assertEquals(5, baos.size());
}

From source file:org.bpmscript.integration.spring.SpringLoanBrokerTest.java

License:asdf

@SuppressWarnings("unchecked")
public void testReply() throws Exception {

    int total = 1;
    final CountDownLatch latch = new CountDownLatch(total);

    final ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
            "/org/bpmscript/integration/spring/spring.xml");

    try {/*from ww w .  jav  a2s  . c o  m*/

        final BpmScriptEngine engine = (BpmScriptEngine) context.getBean("engine");
        final IVersionedDefinitionManager processManager = (IVersionedDefinitionManager) context
                .getBean("versionedDefinitionManager");
        final ChannelRegistry channelRegistry = (ChannelRegistry) ((Map) context
                .getBeansOfType(ChannelRegistry.class)).values().iterator().next();

        processManager.createDefinition("id",
                new JavascriptProcessDefinition("loanBroker", StreamService.DEFAULT_INSTANCE
                        .getResourceAsString("/org/bpmscript/integration/spring/loanbroker.js")));
        engine.setInstanceListener(new LoggingInstanceListener() {
            @Override
            public void instanceCompleted(String pid, ICompletedResult result) {
                super.instanceCompleted(pid, result);
                latch.countDown();
            }

            @Override
            public void instanceFailed(String pid, IFailedResult result) {
                super.instanceFailed(pid, result);
                fail(result.getThrowable().getMessage());
            }
        });

        IBenchmarkPrinter.STDOUT.print(new Benchmark().execute(total, new IBenchmarkCallback() {
            @SuppressWarnings("unchecked")
            public void execute(int count) throws Exception {
                GenericMessage<Object[]> message = new GenericMessage<Object[]>(
                        new Object[] { new LoanRequest("asdf", 1, 1000) });
                message.getHeader().setAttribute("definitionName", "loanBroker");
                message.getHeader().setAttribute("operation", "requestBestRate");
                message.getHeader().setReturnAddress("channel-recorder");
                MessageChannel channel = channelRegistry.lookupChannel("channel-bpmscript-first");
                channel.send(message);
            }
        }, new IWaitForCallback() {
            public void call() throws Exception {
                latch.await();
            }
        }, false));

        SpringRecorder springRecorder = (SpringRecorder) context.getBean("springRecorder");
        BlockingQueue<Object> messages = springRecorder.getMessages();
        for (int i = 0; i < total; i++) {
            Object poll = messages.poll(1, TimeUnit.SECONDS);
            assertNotNull("should have got to " + total + " but got to " + i, poll);
        }

    } finally {
        context.destroy();
    }

}

From source file:org.bpmscript.integration.internal.memory.BpmScriptTestSupport.java

/**
 * @see org.bpmscript.test.ITestSupport#execute(org.bpmscript.test.ITestCallback)
 *//*from  ww w .  j  a va 2 s  . c  o m*/
public void execute(final ITestCallback<ApplicationContext> callback) throws Exception {
    final CountDownLatch latch = new CountDownLatch(total);
    final ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(spring);
    try {
        final BpmScriptEngine engine = (BpmScriptEngine) context.getBean("engine");
        final IVersionedDefinitionManager processManager = (IVersionedDefinitionManager) context
                .getBean("versionedDefinitionManager");
        processManager.createDefinition("id", new JavascriptProcessDefinition("test",
                StreamService.DEFAULT_INSTANCE.getResourceAsString(script)));
        engine.setInstanceListener(new LoggingInstanceListener() {
            @Override
            public void instanceCompleted(String pid, ICompletedResult result) {
                super.instanceCompleted(pid, result);
                latch.countDown();
            }
        });
        IBenchmarkPrinter.STDOUT.print(new Benchmark().execute(total, new IBenchmarkCallback() {
            public void execute(int count) throws Exception {
                callback.execute(context);
            }
        }, new IWaitForCallback() {
            public void call() throws Exception {
                latch.await();
            }
        }, false));
    } finally {
        context.destroy();
    }
}

From source file:io.fabric8.msg.jnatsd.TestNullPayload.java

@Test
public void testNullPayload() throws Exception {
    Connection connection = connectionFactory.createConnection();
    final int count = 100;
    CountDownLatch countDownLatch = new CountDownLatch(count);
    Subscription subscription = connection.subscribe("foo", new MessageHandler() {
        @Override/*from  ww w.  j  a v  a  2 s.  c o  m*/
        public void onMessage(Message message) {
            countDownLatch.countDown();
        }
    });

    for (int i = 0; i < count; i++) {
        connection.publish("foo", null);
    }

    countDownLatch.await(10, TimeUnit.SECONDS);
    Assert.assertEquals(0, countDownLatch.getCount());
    connection.close();
}

From source file:CountUpDownLatch.java

public void countUp() {

    if (latch.getCount() == 0) {
        latch = new CountDownLatch(1);
    }

    count++;
}