Example usage for java.util.concurrent CountDownLatch getCount

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

Introduction

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

Prototype

public long getCount() 

Source Link

Document

Returns the current count.

Usage

From source file:org.springframework.cloud.stream.binder.rabbit.RabbitBinderTests.java

@Test
public void testAutoBindDLQPartitionedProducerFirst() throws Exception {
    RabbitTestBinder binder = getBinder();
    ExtendedProducerProperties<RabbitProducerProperties> properties = createProducerProperties();

    properties.getExtension().setPrefix("bindertest.");
    properties.getExtension().setAutoBindDlq(true);
    properties.setRequiredGroups("dlqPartGrp");
    properties.setPartitionKeyExtractorClass(PartitionTestSupport.class);
    properties.setPartitionSelectorClass(PartitionTestSupport.class);
    properties.setPartitionCount(2);//from w w w.  j  a v  a2s. c  o  m
    DirectChannel output = createBindableChannel("output", createProducerBindingProperties(properties));
    output.setBeanName("test.output");
    Binding<MessageChannel> outputBinding = binder.bindProducer("partDLQ.1", output, properties);

    ExtendedConsumerProperties<RabbitConsumerProperties> consumerProperties = createConsumerProperties();
    consumerProperties.getExtension().setPrefix("bindertest.");
    consumerProperties.getExtension().setAutoBindDlq(true);
    consumerProperties.setMaxAttempts(1); // disable retry
    consumerProperties.setPartitioned(true);
    consumerProperties.setInstanceIndex(0);
    DirectChannel input0 = createBindableChannel("input", createConsumerBindingProperties(consumerProperties));
    input0.setBeanName("test.input0DLQ");
    Binding<MessageChannel> input0Binding = binder.bindConsumer("partDLQ.1", "dlqPartGrp", input0,
            consumerProperties);
    Binding<MessageChannel> defaultConsumerBinding1 = binder.bindConsumer("partDLQ.1", "defaultConsumer",
            new QueueChannel(), consumerProperties);
    consumerProperties.setInstanceIndex(1);
    DirectChannel input1 = createBindableChannel("input1", createConsumerBindingProperties(consumerProperties));
    input1.setBeanName("test.input1DLQ");
    Binding<MessageChannel> input1Binding = binder.bindConsumer("partDLQ.1", "dlqPartGrp", input1,
            consumerProperties);
    Binding<MessageChannel> defaultConsumerBinding2 = binder.bindConsumer("partDLQ.1", "defaultConsumer",
            new QueueChannel(), consumerProperties);

    final CountDownLatch latch0 = new CountDownLatch(1);
    input0.subscribe(new MessageHandler() {

        @Override
        public void handleMessage(Message<?> message) throws MessagingException {
            if (latch0.getCount() <= 0) {
                throw new RuntimeException("dlq");
            }
            latch0.countDown();
        }

    });

    final CountDownLatch latch1 = new CountDownLatch(1);
    input1.subscribe(new MessageHandler() {

        @Override
        public void handleMessage(Message<?> message) throws MessagingException {
            if (latch1.getCount() <= 0) {
                throw new RuntimeException("dlq");
            }
            latch1.countDown();
        }

    });

    output.send(new GenericMessage<Integer>(1));
    assertThat(latch1.await(10, TimeUnit.SECONDS)).isTrue();

    output.send(new GenericMessage<Integer>(0));
    assertThat(latch0.await(10, TimeUnit.SECONDS)).isTrue();

    output.send(new GenericMessage<Integer>(1));

    RabbitTemplate template = new RabbitTemplate(this.rabbitAvailableRule.getResource());
    template.setReceiveTimeout(10000);

    String streamDLQName = "bindertest.partDLQ.1.dlqPartGrp.dlq";

    org.springframework.amqp.core.Message received = template.receive(streamDLQName);
    assertThat(received).isNotNull();
    assertThat(received.getMessageProperties().getReceivedRoutingKey())
            .isEqualTo("bindertest.partDLQ.1.dlqPartGrp-1");
    assertThat(received.getMessageProperties().getHeaders()).doesNotContainKey(BinderHeaders.PARTITION_HEADER);
    assertThat(received.getMessageProperties().getReceivedDeliveryMode())
            .isEqualTo(MessageDeliveryMode.PERSISTENT);

    output.send(new GenericMessage<Integer>(0));
    received = template.receive(streamDLQName);
    assertThat(received).isNotNull();
    assertThat(received.getMessageProperties().getReceivedRoutingKey())
            .isEqualTo("bindertest.partDLQ.1.dlqPartGrp-0");
    assertThat(received.getMessageProperties().getHeaders()).doesNotContainKey(BinderHeaders.PARTITION_HEADER);

    input0Binding.unbind();
    input1Binding.unbind();
    defaultConsumerBinding1.unbind();
    defaultConsumerBinding2.unbind();
    outputBinding.unbind();
}

From source file:org.apache.tinkerpop.gremlin.groovy.engine.GremlinExecutorTest.java

@Test
public void shouldTimeoutSleepingScript() throws Exception {
    final AtomicBoolean successCalled = new AtomicBoolean(false);
    final AtomicBoolean failureCalled = new AtomicBoolean(false);

    final CountDownLatch timeOutCount = new CountDownLatch(1);

    final GremlinExecutor gremlinExecutor = GremlinExecutor.build().scriptEvaluationTimeout(250)
            .afterFailure((b, e) -> failureCalled.set(true)).afterSuccess((b) -> successCalled.set(true))
            .afterTimeout((b) -> timeOutCount.countDown()).create();
    try {/*  w w w  .ja va 2  s . c  o  m*/
        gremlinExecutor.eval("Thread.sleep(1000);10").get();
        fail("This script should have timed out with an exception");
    } catch (Exception ex) {
        assertEquals(TimeoutException.class, ex.getCause().getClass());
    }

    assertTrue(timeOutCount.await(2000, TimeUnit.MILLISECONDS));

    assertFalse(successCalled.get());
    assertFalse(failureCalled.get());
    assertEquals(0, timeOutCount.getCount());
    gremlinExecutor.close();
}

From source file:org.springframework.cloud.stream.binder.rabbit.RabbitBinderTests.java

private void testAutoBindDLQPartionedConsumerFirstWithRepublishGuts(final boolean withRetry) throws Exception {
    RabbitTestBinder binder = getBinder();
    ExtendedConsumerProperties<RabbitConsumerProperties> properties = createConsumerProperties();
    properties.getExtension().setPrefix("bindertest.");
    properties.getExtension().setAutoBindDlq(true);
    properties.getExtension().setRepublishToDlq(true);
    properties.getExtension().setRepublishDeliveyMode(MessageDeliveryMode.NON_PERSISTENT);
    properties.setMaxAttempts(withRetry ? 2 : 1);
    properties.setPartitioned(true);//w w  w .j a va  2s.co m
    properties.setInstanceIndex(0);
    DirectChannel input0 = createBindableChannel("input", createConsumerBindingProperties(properties));
    input0.setBeanName("test.input0DLQ");
    Binding<MessageChannel> input0Binding = binder.bindConsumer("partPubDLQ.0", "dlqPartGrp", input0,
            properties);
    Binding<MessageChannel> defaultConsumerBinding1 = binder.bindConsumer("partPubDLQ.0", "default",
            new QueueChannel(), properties);
    properties.setInstanceIndex(1);
    DirectChannel input1 = createBindableChannel("input1", createConsumerBindingProperties(properties));
    input1.setBeanName("test.input1DLQ");
    Binding<MessageChannel> input1Binding = binder.bindConsumer("partPubDLQ.0", "dlqPartGrp", input1,
            properties);
    Binding<MessageChannel> defaultConsumerBinding2 = binder.bindConsumer("partPubDLQ.0", "default",
            new QueueChannel(), properties);

    ExtendedProducerProperties<RabbitProducerProperties> producerProperties = createProducerProperties();
    producerProperties.getExtension().setPrefix("bindertest.");
    producerProperties.getExtension().setAutoBindDlq(true);
    producerProperties.setPartitionKeyExtractorClass(PartitionTestSupport.class);
    producerProperties.setPartitionSelectorClass(PartitionTestSupport.class);
    producerProperties.setPartitionCount(2);
    BindingProperties bindingProperties = createProducerBindingProperties(producerProperties);
    DirectChannel output = createBindableChannel("output", bindingProperties);
    output.setBeanName("test.output");
    Binding<MessageChannel> outputBinding = binder.bindProducer("partPubDLQ.0", output, producerProperties);

    final CountDownLatch latch0 = new CountDownLatch(1);
    input0.subscribe(new MessageHandler() {

        @Override
        public void handleMessage(Message<?> message) throws MessagingException {
            if (latch0.getCount() <= 0) {
                throw new RuntimeException("dlq");
            }
            latch0.countDown();
        }

    });

    final CountDownLatch latch1 = new CountDownLatch(1);
    input1.subscribe(new MessageHandler() {

        @Override
        public void handleMessage(Message<?> message) throws MessagingException {
            if (latch1.getCount() <= 0) {
                throw new RuntimeException("dlq");
            }
            latch1.countDown();
        }

    });

    ApplicationContext context = TestUtils.getPropertyValue(binder.getBinder(), "applicationContext",
            ApplicationContext.class);
    SubscribableChannel boundErrorChannel = context.getBean("bindertest.partPubDLQ.0.dlqPartGrp-0.errors",
            SubscribableChannel.class);
    SubscribableChannel globalErrorChannel = context.getBean("errorChannel", SubscribableChannel.class);
    final AtomicReference<Message<?>> boundErrorChannelMessage = new AtomicReference<>();
    final AtomicReference<Message<?>> globalErrorChannelMessage = new AtomicReference<>();
    final AtomicBoolean hasRecovererInCallStack = new AtomicBoolean(!withRetry);
    boundErrorChannel.subscribe(new MessageHandler() {

        @Override
        public void handleMessage(Message<?> message) throws MessagingException {
            boundErrorChannelMessage.set(message);
            String stackTrace = Arrays.toString(new RuntimeException().getStackTrace());
            hasRecovererInCallStack.set(stackTrace.contains("ErrorMessageSendingRecoverer"));
        }

    });
    globalErrorChannel.subscribe(new MessageHandler() {

        @Override
        public void handleMessage(Message<?> message) throws MessagingException {
            globalErrorChannelMessage.set(message);
        }

    });

    output.send(new GenericMessage<>(1));
    assertThat(latch1.await(10, TimeUnit.SECONDS)).isTrue();

    output.send(new GenericMessage<>(0));
    assertThat(latch0.await(10, TimeUnit.SECONDS)).isTrue();

    output.send(new GenericMessage<>(1));

    RabbitTemplate template = new RabbitTemplate(this.rabbitAvailableRule.getResource());
    template.setReceiveTimeout(10000);

    String streamDLQName = "bindertest.partPubDLQ.0.dlqPartGrp.dlq";

    org.springframework.amqp.core.Message received = template.receive(streamDLQName);
    assertThat(received).isNotNull();
    assertThat(received.getMessageProperties().getHeaders().get("x-original-routingKey"))
            .isEqualTo("partPubDLQ.0-1");
    assertThat(received.getMessageProperties().getHeaders()).doesNotContainKey(BinderHeaders.PARTITION_HEADER);
    assertThat(received.getMessageProperties().getReceivedDeliveryMode())
            .isEqualTo(MessageDeliveryMode.NON_PERSISTENT);

    output.send(new GenericMessage<>(0));
    received = template.receive(streamDLQName);
    assertThat(received).isNotNull();
    assertThat(received.getMessageProperties().getHeaders().get("x-original-routingKey"))
            .isEqualTo("partPubDLQ.0-0");
    assertThat(received.getMessageProperties().getHeaders()).doesNotContainKey(BinderHeaders.PARTITION_HEADER);

    // verify we got a message on the dedicated error channel and the global (via bridge)
    assertThat(boundErrorChannelMessage.get()).isNotNull();
    assertThat(globalErrorChannelMessage.get()).isNotNull();
    assertThat(hasRecovererInCallStack.get()).isEqualTo(withRetry);

    input0Binding.unbind();
    input1Binding.unbind();
    defaultConsumerBinding1.unbind();
    defaultConsumerBinding2.unbind();
    outputBinding.unbind();
}

From source file:io.undertow.server.handlers.sse.ServerSentEventTestCase.java

@Test
public void testConnectionFail() throws IOException, InterruptedException {

    final Socket socket = new Socket(DefaultServer.getHostAddress("default"),
            DefaultServer.getHostPort("default"));
    final CountDownLatch latch = new CountDownLatch(1);
    final CountDownLatch connected = new CountDownLatch(1);
    DefaultServer.setRootHandler(new ServerSentEventHandler(new ServerSentEventConnectionCallback() {
        @Override/*from ww w  .  j ava  2  s . c  o m*/
        public void connected(final ServerSentEventConnection connection, final String lastEventId) {
            final XnioIoThread thread = (XnioIoThread) Thread.currentThread();
            connected.countDown();
            thread.execute(new Runnable() {
                @Override
                public void run() {
                    connection.send("hello", new ServerSentEventConnection.EventCallback() {
                        @Override
                        public void done(ServerSentEventConnection connection, String data, String event,
                                String id) {
                        }

                        @Override
                        public void failed(ServerSentEventConnection connection, String data, String event,
                                String id, IOException e) {
                            latch.countDown();
                        }
                    });
                    if (latch.getCount() > 0) {
                        WorkerUtils.executeAfter(thread, this, 100, TimeUnit.MILLISECONDS);
                    }
                }
            });
        }
    }));
    InputStream in = socket.getInputStream();
    OutputStream out = socket.getOutputStream();
    out.write(("GET / HTTP/1.1\r\nHost:" + DefaultServer.getHostAddress() + "\r\n\r\n").getBytes());
    out.flush();
    if (!connected.await(10, TimeUnit.SECONDS)) {
        Assert.fail();
    }
    out.close();
    in.close();
    if (!latch.await(10, TimeUnit.SECONDS)) {
        Assert.fail();
    }
}

From source file:org.apache.sshd.PortForwardingTest.java

@Test
@Ignore//from ww  w  .j  a  va2s  .com
public void testForwardingOnLoad() throws Exception {
    //        final String path = "/history/recent/troubles/";
    //        final String host = "www.bbc.co.uk";
    //        final String path = "";
    //        final String host = "www.bahn.de";
    final String path = "";
    final String host = "localhost";
    final int nbThread = 2;
    final int nbDownloads = 2;
    final int nbLoops = 2;

    final int port = getFreePort();
    StringBuilder resp = new StringBuilder();
    resp.append("<html><body>\n");
    for (int i = 0; i < 1000; i++) {
        resp.append("0123456789\n");
    }
    resp.append("</body></html>\n");
    final StringBuilder sb = new StringBuilder();
    sb.append("HTTP/1.1 200 OK").append('\n');
    sb.append("Content-Type: text/HTML").append('\n');
    sb.append("Content-Length: ").append(resp.length()).append('\n');
    sb.append('\n');
    sb.append(resp);
    NioSocketAcceptor acceptor = new NioSocketAcceptor();
    acceptor.setHandler(new IoHandlerAdapter() {
        @Override
        public void messageReceived(IoSession session, Object message) throws Exception {
            session.write(IoBuffer.wrap(sb.toString().getBytes()));
        }
    });
    acceptor.setReuseAddress(true);
    acceptor.bind(new InetSocketAddress(port));

    Session session = createSession();

    final int forwardedPort1 = getFreePort();
    final int forwardedPort2 = getFreePort();
    System.err.println("URL: http://localhost:" + forwardedPort2);

    session.setPortForwardingL(forwardedPort1, host, port);
    session.setPortForwardingR(forwardedPort2, "localhost", forwardedPort1);

    final CountDownLatch latch = new CountDownLatch(nbThread * nbDownloads * nbLoops);

    final Thread[] threads = new Thread[nbThread];
    final List<Throwable> errors = new CopyOnWriteArrayList<Throwable>();
    for (int i = 0; i < threads.length; i++) {
        threads[i] = new Thread() {
            public void run() {
                for (int j = 0; j < nbLoops; j++) {
                    final MultiThreadedHttpConnectionManager mgr = new MultiThreadedHttpConnectionManager();
                    final HttpClient client = new HttpClient(mgr);
                    client.getHttpConnectionManager().getParams().setDefaultMaxConnectionsPerHost(100);
                    client.getHttpConnectionManager().getParams().setMaxTotalConnections(1000);
                    for (int i = 0; i < nbDownloads; i++) {
                        try {
                            checkHtmlPage(client, new URL("http://localhost:" + forwardedPort2 + path));
                        } catch (Throwable e) {
                            errors.add(e);
                        } finally {
                            latch.countDown();
                            System.err.println("Remaining: " + latch.getCount());
                        }
                    }
                    mgr.shutdown();
                }
            }
        };
    }
    for (int i = 0; i < threads.length; i++) {
        threads[i].start();
    }
    latch.await();
    for (Throwable t : errors) {
        t.printStackTrace();
    }
    assertEquals(0, errors.size());
}

From source file:org.apache.sshd.PortForwardingLoadTest.java

@Test
public void testForwardingOnLoad() throws Exception {
    //        final String path = "/history/recent/troubles/";
    //        final String host = "www.bbc.co.uk";
    //        final String path = "";
    //        final String host = "www.bahn.de";
    final String path = "";
    final String host = "localhost";
    final int nbThread = 2;
    final int nbDownloads = 2;
    final int nbLoops = 2;

    final int port = getFreePort();
    StringBuilder resp = new StringBuilder();
    resp.append("<html><body>\n");
    for (int i = 0; i < 1000; i++) {
        resp.append("0123456789\n");
    }//from  w  w  w  .j  a  va2 s  .  c  o  m
    resp.append("</body></html>\n");
    final StringBuilder sb = new StringBuilder();
    sb.append("HTTP/1.1 200 OK").append('\n');
    sb.append("Content-Type: text/HTML").append('\n');
    sb.append("Content-Length: ").append(resp.length()).append('\n');
    sb.append('\n');
    sb.append(resp);
    NioSocketAcceptor acceptor = new NioSocketAcceptor();
    acceptor.setHandler(new IoHandlerAdapter() {
        @Override
        public void messageReceived(IoSession session, Object message) throws Exception {
            session.write(IoBuffer.wrap(sb.toString().getBytes()));
        }
    });
    acceptor.setReuseAddress(true);
    acceptor.bind(new InetSocketAddress(port));

    Session session = createSession();

    final int forwardedPort1 = getFreePort();
    final int forwardedPort2 = getFreePort();
    System.err.println("URL: http://localhost:" + forwardedPort2);

    session.setPortForwardingL(forwardedPort1, host, port);
    session.setPortForwardingR(forwardedPort2, "localhost", forwardedPort1);

    final CountDownLatch latch = new CountDownLatch(nbThread * nbDownloads * nbLoops);

    final Thread[] threads = new Thread[nbThread];
    final List<Throwable> errors = new CopyOnWriteArrayList<Throwable>();
    for (int i = 0; i < threads.length; i++) {
        threads[i] = new Thread() {
            public void run() {
                for (int j = 0; j < nbLoops; j++) {
                    final MultiThreadedHttpConnectionManager mgr = new MultiThreadedHttpConnectionManager();
                    final HttpClient client = new HttpClient(mgr);
                    client.getHttpConnectionManager().getParams().setDefaultMaxConnectionsPerHost(100);
                    client.getHttpConnectionManager().getParams().setMaxTotalConnections(1000);
                    for (int i = 0; i < nbDownloads; i++) {
                        try {
                            checkHtmlPage(client, new URL("http://localhost:" + forwardedPort2 + path));
                        } catch (Throwable e) {
                            errors.add(e);
                        } finally {
                            latch.countDown();
                            System.err.println("Remaining: " + latch.getCount());
                        }
                    }
                    mgr.shutdown();
                }
            }
        };
    }
    for (int i = 0; i < threads.length; i++) {
        threads[i].start();
    }
    latch.await();
    for (Throwable t : errors) {
        t.printStackTrace();
    }
    assertEquals(0, errors.size());
}

From source file:org.mskcc.shenkers.view.IntervalViewNGTest.java

public void testIntervalView() throws InterruptedException {
    System.out.println("testIntervalView");
    Pane p = new Pane();

    CountDownLatch l = new CountDownLatch(1);
    System.out.println("before");
    Platform.runLater(() -> {//from w  w w . ja va 2s  . c  o  m
        System.out.println("running");
        double[][] intervals = { { .1, .2 } };
        //                    Range r = null;
        RangeSet<Double> rs = TreeRangeSet.create();
        rs.add(Range.closed(.1, .2));
        rs.add(Range.closed(.2, .3));
        rs.add(Range.closed(.32, .35));
        rs.add(Range.closed(.6, .8));

        for (Range<Double> r : rs.asRanges()) {
            System.out.println(r.lowerEndpoint() + " - " + r.upperEndpoint());
        }
        for (Range<Double> interval : rs.asRanges()) {
            Rectangle r = new Rectangle();
            r.widthProperty()
                    .bind(p.widthProperty().multiply(interval.upperEndpoint() - interval.lowerEndpoint()));
            r.heightProperty().bind(p.heightProperty());
            r.xProperty().bind(p.widthProperty().multiply(interval.lowerEndpoint()));
            p.getChildren().add(r);
        }
        //                    p.prefTileHeightProperty().bind(p.heightProperty());
        Stage stage = new Stage();
        stage.setOnHidden(e -> {
            l.countDown();
            System.out.println("count " + l.getCount());
        });
        Scene scene = new Scene(p, 300, 300, Color.GRAY);
        stage.setTitle("JavaFX Scene Graph Demo");
        stage.setScene(scene);
        stage.show();

    });
    System.out.println("after");
    l.await();
    Thread.sleep(1000);
}

From source file:org.springframework.amqp.rabbit.core.RabbitTemplatePublisherCallbacksIntegrationTests.java

@Test
public void testPublisherConfirmReceived() throws Exception {
    final CountDownLatch latch = new CountDownLatch(10000);
    final AtomicInteger acks = new AtomicInteger();
    templateWithConfirmsEnabled.setConfirmCallback((correlationData, ack, cause) -> {
        acks.incrementAndGet();/*from   w ww .  j  a va  2 s .  co  m*/
        latch.countDown();
    });
    ExecutorService exec = Executors.newCachedThreadPool();
    for (int i = 0; i < 100; i++) {
        exec.submit(() -> {
            try {
                for (int i1 = 0; i1 < 100; i1++) {
                    templateWithConfirmsEnabled.convertAndSend(ROUTE, (Object) "message",
                            new CorrelationData("abc"));
                }
            } catch (Throwable t) {
                t.printStackTrace();
            }
        });
    }
    exec.shutdown();
    assertTrue(exec.awaitTermination(300, TimeUnit.SECONDS));
    assertTrue("" + latch.getCount(), latch.await(60, TimeUnit.SECONDS));
    assertNull(templateWithConfirmsEnabled.getUnconfirmed(-1));
    this.templateWithConfirmsEnabled.execute(channel -> {
        Map<?, ?> listenerMap = TestUtils.getPropertyValue(((ChannelProxy) channel).getTargetChannel(),
                "listenerForSeq", Map.class);
        int n = 0;
        while (n++ < 100 && listenerMap.size() > 0) {
            Thread.sleep(100);
        }
        assertEquals(0, listenerMap.size());
        return null;
    });

    Log logger = spy(TestUtils.getPropertyValue(connectionFactoryWithConfirmsEnabled, "logger", Log.class));
    new DirectFieldAccessor(connectionFactoryWithConfirmsEnabled).setPropertyValue("logger", logger);
    cleanUp();
    verify(logger, never()).error(any());
}

From source file:org.apache.awf.web.SystemTest.java

@Test
public void callbackTest() throws InterruptedException {
    final CountDownLatch latch = new CountDownLatch(5);
    final AsyncCallback cb = new AsyncCallback() {

        @Override/*ww w.  j  ava 2 s .co m*/
        public void onCallback() {
            latch.countDown();
        }

    };
    IOLoop.INSTANCE.addCallback(cb);
    IOLoop.INSTANCE.addCallback(cb);
    IOLoop.INSTANCE.addCallback(cb);
    IOLoop.INSTANCE.addCallback(cb);
    IOLoop.INSTANCE.addCallback(cb);

    latch.await(5 * 1000, TimeUnit.MILLISECONDS);
    assertTrue(latch.getCount() == 0);
}

From source file:org.alfresco.repo.transaction.RetryingTransactionHelperTest.java

@SuppressWarnings("unchecked")
private void runThreads(final RetryingTransactionHelper txnHelper, final List<Throwable> caughtExceptions,
        final Pair<Integer, Integer>... startDurationPairs) {
    ExecutorService executorService = new ThreadPoolExecutor(10, 10, 0L, TimeUnit.MILLISECONDS,
            new ArrayBlockingQueue<Runnable>(10));

    class Work implements Runnable {
        private final CountDownLatch startLatch;
        private final long endTime;

        public Work(CountDownLatch startLatch, long endTime) {
            this.startLatch = startLatch;
            this.endTime = endTime;
        }//from   ww w. j  av  a 2s . c o  m

        public void run() {
            try {
                txnHelper.doInTransaction(new RetryingTransactionCallback<Void>() {

                    public Void execute() throws Throwable {
                        // Signal that we've started
                        startLatch.countDown();

                        long duration = endTime - System.currentTimeMillis();
                        if (duration > 0) {
                            Thread.sleep(duration);
                        }
                        return null;
                    }
                });
            } catch (Throwable e) {
                caughtExceptions.add(e);
                // We never got a chance to signal we had started so do it now
                if (startLatch.getCount() > 0) {
                    startLatch.countDown();
                }
            }
        }
    }
    ;

    // Schedule the transactions at their required start times
    long startTime = System.currentTimeMillis();
    long currentStart = 0;
    for (Pair<Integer, Integer> pair : startDurationPairs) {
        int start = pair.getFirst();
        long now = System.currentTimeMillis();
        long then = startTime + start;
        if (then > now) {
            try {
                Thread.sleep(then - now);
            } catch (InterruptedException e) {
            }
            currentStart = start;
        }
        CountDownLatch startLatch = new CountDownLatch(1);
        Runnable work = new Work(startLatch, startTime + currentStart + pair.getSecond());
        executorService.execute(work);
        try {
            // Wait for the thread to get up and running. We need them starting in sequence
            startLatch.await(60, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
        }
    }
    // Wait for the threads to have finished
    executorService.shutdown();
    try {
        executorService.awaitTermination(60, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
    }

}