Package edu.emory.mathcs.backport.java.util.concurrent

Examples of edu.emory.mathcs.backport.java.util.concurrent.CountDownLatch


                new Byte(ActiveMQDestination.TEMP_TOPIC_TYPE) });
    }
    public void testMessageListenerWithConsumer() throws Exception {

        final AtomicInteger counter = new AtomicInteger(0);
        final CountDownLatch done = new CountDownLatch(1);
       
        // Receive a message with the JMS API
        connection.start();
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        destination = createDestination(session, destinationType);
        MessageConsumer consumer = session.createConsumer(destination);
        consumer.setMessageListener(new MessageListener() {
            public void onMessage(Message m) {
                counter.incrementAndGet();
                if( counter.get()==4 )
                    done.countDown();
            }
        });

        // Send the messages
        sendMessages(session, destination, 4);

        assertTrue(done.await(1000, TimeUnit.MILLISECONDS));
        Thread.sleep(200);
       
        // Make sure only 4 messages were delivered.
        assertEquals(4, counter.get());
    }
View Full Code Here


     */
    public void testConcurrentSendReceive() throws Throwable {

        final Semaphore connectionsEstablished = new Semaphore(1 - (CONSUMER_COUNT + PRODUCER_COUNT));
        final Semaphore workerDone = new Semaphore(1 - (CONSUMER_COUNT + PRODUCER_COUNT));
        final CountDownLatch sampleTimeDone = new CountDownLatch(1);

        final AtomicInteger producedMessages = new AtomicInteger(0);
        final AtomicInteger receivedMessages = new AtomicInteger(0);

        final Callable producer = new Callable() {
            public Object call() throws JMSException, InterruptedException {
                Connection connection = factory.createConnection();
                connections.add(connection);
                Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
                MessageProducer producer = session.createProducer(destination);
                producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
                BytesMessage message = session.createBytesMessage();
                message.writeBytes(new byte[1024]);
                connection.start();
                connectionsEstablished.release();

                while (!sampleTimeDone.await(0, TimeUnit.MILLISECONDS)) {
                    producer.send(message);
                    producedMessages.incrementAndGet();
                }

                connection.close();
                workerDone.release();
                return null;
            }
        };

        final Callable consumer = new Callable() {
            public Object call() throws JMSException, InterruptedException {
                Connection connection = factory.createConnection();
                connections.add(connection);
                Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
                MessageConsumer consumer = session.createConsumer(destination);

                consumer.setMessageListener(new MessageListener() {
                    public void onMessage(Message msg) {
                        receivedMessages.incrementAndGet();
                    }
                });
                connection.start();

                connectionsEstablished.release();
                sampleTimeDone.await();

                connection.close();
                workerDone.release();
                return null;
            }
        };

        final Throwable workerError[] = new Throwable[1];
        for (int i = 0; i < PRODUCER_COUNT; i++) {
            new Thread("Producer:" + i) {
                public void run() {
                    try {
                        producer.call();
                    } catch (Throwable e) {
                        e.printStackTrace();
                        workerError[0] = e;
                    }
                }
            }.start();
        }

        for (int i = 0; i < CONSUMER_COUNT; i++) {
            new Thread("Consumer:" + i) {
                public void run() {
                    try {
                        consumer.call();
                    } catch (Throwable e) {
                        e.printStackTrace();
                        workerError[0] = e;
                    }
                }
            }.start();
        }

        System.out.println(getName() + ": Waiting for Producers and Consumers to startup.");
        connectionsEstablished.acquire();
        System.out.println("Producers and Consumers are now running.  Waiting for system to reach steady state: "
                + (SAMPLE_DELAY / 1000.0f) + " seconds");
        Thread.sleep(1000 * 10);

        System.out.println("Starting sample: "+SAMPLES+" each lasting "+ (SAMPLE_DURATION / 1000.0f) + " seconds");


        long now = System.currentTimeMillis();
        for( int i=0; i < SAMPLES; i ++) {
           
            long start = System.currentTimeMillis();
            producedMessages.set(0);
            receivedMessages.set(0);
           
            Thread.sleep(SAMPLE_DURATION);
           
            long end = System.currentTimeMillis();
            int r = receivedMessages.get();
            int p = producedMessages.get();
           
            System.out.println("published: " + p + " msgs at "+ (p * 1000f / (end - start)) + " msgs/sec, "+
                    "consumed: " + r + " msgs at "+ (r * 1000f / (end - start)) + " msgs/sec");
        }

        System.out.println("Sample done.");
        sampleTimeDone.countDown();

        workerDone.acquire();
        if (workerError[0] != null) {
            throw workerError[0];
        }
View Full Code Here

            int th = 30;
            if (args.length > 1) {
                th = Integer.parseInt(args[1]);
            }
            GeronimoWorkManager wm = createWorkManager(th);
            latch = new CountDownLatch(nb);
            for (int i = 0; i < nb; i++) {
                wm.scheduleWork(new JMSClient());
            }
            latch.await();
            wm.doStop();
View Full Code Here

    /* (non-Javadoc)
     * @see javax.resource.spi.work.WorkManager#startWork(javax.resource.spi.work.Work)
     */
    public long startWork(final Work work) throws WorkException {
        final CountDownLatch latch = new CountDownLatch(1);
        executor.execute(new Work() {
            public void release() {
                work.release();
            }
            public void run() {
                latch.countDown();
                work.run();
            }
        });
        long t = System.currentTimeMillis();
        try {
            latch.await();
        } catch (InterruptedException e) {
            throw new WorkException("Interrupted", e);
        }
        return System.currentTimeMillis() - t;
    }
View Full Code Here

     * @param msgContext the message context
     * @return an object that implements the service
     * @throws AxisFault if fails
     */
    protected static Object makeNewServiceObject(MessageContext msgContext) throws AxisFault {
        CountDownLatch startLatch = new CountDownLatch(1);
        CountDownLatch stopLatch = new CountDownLatch(1);
        EJBClientWorker worker = new EJBClientWorker(msgContext, startLatch, stopLatch);
        workerPool.execute(worker);
        startLatch.countDown();
        try {
            stopLatch.await();
        } catch (InterruptedException e) {
            throw AxisFault.makeFault(e);
        }

        if (worker.getException() != null) {
View Full Code Here

public class VmPipeSessionCrossCommunicationTest extends TestCase {
    public void testOneSessionTalkingBackAndForthDoesNotDeadlock() throws Exception {
        final VmPipeAddress address = new VmPipeAddress( 1 );
        final IoConnector connector = new VmPipeConnector();
        final AtomicReference c1 = new AtomicReference();
        final CountDownLatch latch = new CountDownLatch( 1 );
        final CountDownLatch messageCount = new CountDownLatch( 2 );
        IoAcceptor acceptor = new VmPipeAcceptor();

        acceptor.bind( address, new IoHandlerAdapter() {
            public void messageReceived( IoSession session, Object message ) throws Exception {
                System.out.println( Thread.currentThread().getName() + ": " + message );

                if ( "start".equals( message ) ) {
                    session.write( "open new" );
                } else if ( "re-use c1".equals( message ) ) {
                    session.write( "tell me something on c1 now" );
                } else if ( ( (String) message ).startsWith( "please don't deadlock" ) ) {
                    messageCount.countDown();
                } else {
                    fail( "unexpected message received " + message );
                }
            }
        } );

        connector.getDefaultConfig().setThreadModel( ThreadModel.MANUAL );

        ConnectFuture future = connector.connect( address, new IoHandlerAdapter() {
            public void messageReceived( IoSession session, Object message ) throws Exception {
                System.out.println( Thread.currentThread().getName() + ": " + message );
               
                if ( "open new".equals( message ) ) {
                    System.out.println( "opening c2 from " + Thread.currentThread().getName() );

                    ConnectFuture c2Future = connector.connect( address, new IoHandlerAdapter() {
                        public void sessionOpened( IoSession session ) throws Exception {
                            session.write( "re-use c1" );
                        }

                        public void messageReceived( IoSession session, Object message ) throws Exception {
                            System.out.println( Thread.currentThread().getName() + ": " + message );

                            if ( "tell me something on c1 now".equals( message ) ) {
                                latch.countDown();
                                ((IoSession) c1.get()).write( "please don't deadlock via c1" );
                            } else {
                                fail( "unexpected message received " + message );
                            }
                        }
                    } );

                    c2Future.join();

                    latch.await();

                    c2Future.getSession().write( "please don't deadlock via c2" );
                } else {
                    fail( "unexpeced message received " + message );
                }
            }
        } );

        future.join();

        c1.set( future.getSession() );
        ((IoSession) c1.get()).write( "start" );

        ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();

        while ( !messageCount.await( 100, TimeUnit.MILLISECONDS ) ) {
            long[] threads = threadMXBean.findMonitorDeadlockedThreads();

            if ( null != threads ) {
                StringBuffer sb = new StringBuffer( 256 );
                ThreadInfo[] infos = threadMXBean.getThreadInfo( threads, Integer.MAX_VALUE );
View Full Code Here

      acf = createConnectionFactory(URL1);
      pcf = new PooledConnectionFactory(acf);

      // Only listen on the first queue.. let the 2nd queue fill up.
      doneLatch = new CountDownLatch(NUM_MESSAGE_TO_SEND);
      container1 = createDefaultMessageListenerContainer(acf,  new TestMessageListener1(500), QUEUE1_NAME);
      container1.afterPropertiesSet();

      Thread.sleep(2000);
View Full Code Here

      pcf = new PooledConnectionFactory(acf1);

      Thread.sleep(1000);

      doneLatch = new CountDownLatch(MAX_PRODUCERS * NUM_MESSAGE_TO_SEND);
      container1 = createDefaultMessageListenerContainer(acf2, new TestMessageListener1(500), QUEUE1_NAME);
      container1.afterPropertiesSet();

      final ExecutorService executor = Executors.newCachedThreadPool();
      for (int i = 0; i < MAX_PRODUCERS; i++) {
View Full Code Here

      acf1 = createConnectionFactory(URL1);
      acf2 = createConnectionFactory(URL2);

      Thread.sleep(1000);

      doneLatch = new CountDownLatch(NUM_MESSAGE_TO_SEND*MAX_PRODUCERS);

      container1 = createDefaultMessageListenerContainer(acf2, new TestMessageListener1(500), QUEUE1_NAME);
      container1.afterPropertiesSet();
      container2 = createDefaultMessageListenerContainer(acf2, new TestMessageListener1(30000), QUEUE2_NAME);
      container2.afterPropertiesSet();
View Full Code Here

    }

    public void testNoConcurrentWorkSameXid() throws Exception {
        final Xid xid = xidFactory.createXid();

        final CountDownLatch startSignal = new CountDownLatch(1);
        final CountDownLatch cleanupSignal = new CountDownLatch(1);
        final CountDownLatch endSignal = new CountDownLatch(1);

        new Thread() {
            public void run() {
                try {
                    try {
                        try {
                            geronimoTransactionManager.begin(xid, 1000);
                        } finally {
                            startSignal.countDown();
                        }
                        cleanupSignal.await();
                        geronimoTransactionManager.end(xid);
                        geronimoTransactionManager.rollback(xid);
                    } finally {
                        endSignal.countDown();
                    }
                } catch (Exception e) {
                    throw (AssertionFailedError) new AssertionFailedError().initCause(e);
                }
            }
        }.start();

        // wait for thread to begin the tx
        startSignal.await();
        try {
            geronimoTransactionManager.begin(xid, 1000);
            fail("should not be able begin same xid twice");
        } catch (ImportedTransactionActiveException e) {
            //expected
        } finally {
            // tell thread to start cleanup (e.g., end and rollback the tx)
            cleanupSignal.countDown();

            // wait for our thread to finish cleanup
            endSignal.await();
        }
    }
View Full Code Here

TOP

Related Classes of edu.emory.mathcs.backport.java.util.concurrent.CountDownLatch

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.