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

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


        try {
            if (journal == null )
                throw new IllegalStateException("Journal is closed.");
           
            long now = System.currentTimeMillis();
            CountDownLatch latch = null;
            synchronized(this) {
                latch = nextCheckpointCountDownLatch;
                lastCheckpointRequest = now;
                if( fullCheckpoint ) {
                    this.fullCheckPoint = true;
                }
            }
           
            checkpointTask.wakeup();
           
            if (sync) {
                log.debug("Waking for checkpoint to complete.");
                latch.await();
            }
        }
        catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            log.warn("Request to start checkpoint failed: " + e, e);
View Full Code Here


    /**
     * This does the actual checkpoint.
     * @return
     */
    public boolean doCheckpoint() {
        CountDownLatch latch = null;
        boolean fullCheckpoint;
        synchronized(this) {                      
            latch = nextCheckpointCountDownLatch;
            nextCheckpointCountDownLatch = new CountDownLatch(1);
            fullCheckpoint = this.fullCheckPoint;
            this.fullCheckPoint=false;           
        }       
        try {

            log.debug("Checkpoint started.");
            RecordLocation newMark = null;

            ArrayList futureTasks = new ArrayList(queues.size()+topics.size());
           
            //
            // We do many partial checkpoints (fullCheckpoint==false) to move topic messages
            // to long term store as soon as possible. 
            //
            // We want to avoid doing that for queue messages since removes the come in the same
            // checkpoint cycle will nullify the previous message add.  Therefore, we only
            // checkpoint queues on the fullCheckpoint cycles.
            //
            if( fullCheckpoint ) {               
                Iterator iterator = queues.values().iterator();
                while (iterator.hasNext()) {
                    try {
                        final QuickJournalMessageStore ms = (QuickJournalMessageStore) iterator.next();
                        FutureTask task = new FutureTask(new Callable() {
                            public Object call() throws Exception {
                                return ms.checkpoint();
                            }});
                        futureTasks.add(task);
                        checkpointExecutor.execute(task);                       
                    }
                    catch (Exception e) {
                        log.error("Failed to checkpoint a message store: " + e, e);
                    }
                }
            }

            Iterator iterator = topics.values().iterator();
            while (iterator.hasNext()) {
                try {
                    final QuickJournalTopicMessageStore ms = (QuickJournalTopicMessageStore) iterator.next();
                    FutureTask task = new FutureTask(new Callable() {
                        public Object call() throws Exception {
                            return ms.checkpoint();
                        }});
                    futureTasks.add(task);
                    checkpointExecutor.execute(task);                       
                }
                catch (Exception e) {
                    log.error("Failed to checkpoint a message store: " + e, e);
                }
            }

            try {
                for (Iterator iter = futureTasks.iterator(); iter.hasNext();) {
                    FutureTask ft = (FutureTask) iter.next();
                    RecordLocation mark = (RecordLocation) ft.get();
                    // We only set a newMark on full checkpoints.
                    if( fullCheckpoint ) {
                        if (mark != null && (newMark == null || newMark.compareTo(mark) < 0)) {
                            newMark = mark;
                        }
                    }
                }
            } catch (Throwable e) {
                log.error("Failed to checkpoint a message store: " + e, e);
            }
           

            if( fullCheckpoint ) {
                try {
                    if (newMark != null) {
                        log.debug("Marking journal at: " + newMark);
                        journal.setMark(newMark, true);
                    }
                }
                catch (Exception e) {
                    log.error("Failed to mark the Journal: " + e, e);
                }
   
                if (longTermPersistence instanceof JDBCPersistenceAdapter) {
                    // We may be check pointing more often than the checkpointInterval if under high use
                    // But we don't want to clean up the db that often.
                    long now = System.currentTimeMillis();
                    if( now > lastCleanup+checkpointInterval ) {
                        lastCleanup = now;
                        ((JDBCPersistenceAdapter) longTermPersistence).cleanup();
                    }
                }
            }

            log.debug("Checkpoint done.");
        }
        finally {
            latch.countDown();
        }
        synchronized(this) {
            return this.fullCheckPoint;
        }       

View Full Code Here

  private AtomicInteger ackCounter = new AtomicInteger(0);
  private CountDownLatch latch;
  private Throwable failure;

  public void testWithReciever() throws Throwable {
    latch = new CountDownLatch(numberOfMessagesOnQueue);
    Session session = connection.createSession(true, 0);
    MessageConsumer consumer = session.createConsumer(destination);

    long start = System.currentTimeMillis();
    while ((System.currentTimeMillis() - start) < 1000*1000) {
View Full Code Here

    fail("Did not receive all the messages.");
  }

  public void testWithMessageListener() throws Throwable {
    latch = new CountDownLatch(numberOfMessagesOnQueue);
    new DelegatingTransactionalMessageListener(this, connection,
        destination);

    long start = System.currentTimeMillis();
    while ((System.currentTimeMillis() - start) < 1000*1000) {
View Full Code Here

        ActiveMQResourceAdapter adapter = new ActiveMQResourceAdapter();
        adapter.setServerUrl("vm://localhost?broker.persistent=false");
        adapter.start(new StubBootstrapContext());

        final CountDownLatch messageDelivered = new CountDownLatch(1);
       
        final StubMessageEndpoint endpoint = new StubMessageEndpoint() {
            public void onMessage(Message message) {
                super.onMessage(message);
                messageDelivered.countDown();
            };
        };
       
        ActiveMQActivationSpec activationSpec = new ActiveMQActivationSpec();
        activationSpec.setDestinationType(Queue.class.getName());
        activationSpec.setDestination("TEST");
        activationSpec.setResourceAdapter(adapter);
        activationSpec.validate();
       
        MessageEndpointFactory messageEndpointFactory = new MessageEndpointFactory() {
            public MessageEndpoint createEndpoint(XAResource resource) throws UnavailableException {
                endpoint.xaresource = resource;
                return endpoint;
            }
            public boolean isDeliveryTransacted(Method method) throws NoSuchMethodException {
                return true;
            }
        };

        // Activate an Endpoint
        adapter.endpointActivation(messageEndpointFactory, activationSpec);
       
        // Give endpoint a chance to setup and register its listeners
        try {
            Thread.sleep(1000);
        } catch (Exception e) {

        }
       
        // Send the broker a message to that endpoint
        MessageProducer producer = session.createProducer(new ActiveMQQueue("TEST"));
        producer.send(session.createTextMessage("Hello!"));
        connection.close();
       
        // Wait for the message to be delivered.
        assertTrue(messageDelivered.await(5000, TimeUnit.MILLISECONDS));
       
        // Shut the Endpoint down.
        adapter.endpointDeactivation(messageEndpointFactory, activationSpec);
        adapter.stop();       
       
View Full Code Here

        } else {
            consumer = session.createConsumer(destination);
        }
        profilerPause("Ready: ");
       
        final CountDownLatch producerDoneLatch = new CountDownLatch(1);
       
        // Send the messages, async
        new Thread() {
            public void run() {
                Connection connection2=null;
                try {
                    connection2 = factory.createConnection();
                    Session session = connection2.createSession(false, Session.AUTO_ACKNOWLEDGE);
                    MessageProducer producer = session.createProducer(destination);
                    producer.setDeliveryMode(deliveryMode);
                    for (int i = 0; i < messageCount; i++) {
                         BytesMessage m = session.createBytesMessage();
                         m.writeBytes(new byte[messageSize]);
                         producer.send(m);
                    }
                    producer.close();
                } catch (JMSException e) {
                    e.printStackTrace();
                } finally {
                    safeClose(connection2);
                    producerDoneLatch.countDown();
                }
               
            }
        }.start();

        // Make sure all the messages were delivered.
        Message message = null;
        for (int i = 0; i < messageCount; i++) {
            message = consumer.receive(5000);
            assertNotNull("Did not get message: "+i, message);
        }

        profilerPause("Done: ");
       
        assertNull(consumer.receiveNoWait());
        message.acknowledge();

        // Make sure the producer thread finishes.
        assertTrue(producerDoneLatch.await(5, TimeUnit.SECONDS));
    }
View Full Code Here

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

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

        // Send a first message to make sure that the consumer dispatcher is running
        sendMessages(session, destination, 1);
        assertTrue(done1.await(1, TimeUnit.SECONDS));
        assertEquals(1, counter.get());

        // Stop the consumer.
        consumer.stop();

        // Send a message, but should not get delivered.
        sendMessages(session, destination, 1);
        assertFalse(done2.await(1, TimeUnit.SECONDS));
        assertEquals(1, counter.get());
       
        // Start the consumer, and the message should now get delivered.
        consumer.start();
        assertTrue(done2.await(1, TimeUnit.SECONDS));
        assertEquals(2, counter.get());
    }
View Full Code Here

                new Byte(ActiveMQDestination.TEMP_TOPIC_TYPE) });
    }
    public void testSetMessageListenerAfterStart() 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);

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

        // See if the message get sent to the listener
        consumer.setMessageListener(new MessageListener() {
            public void onMessage(Message m) {
                counter.incrementAndGet();
                if( counter.get()==4 )
                    done.countDown();
            }
        });

        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 testMessageListenerUnackedWithPrefetch1StayInQueue() throws Exception {

        final AtomicInteger counter = new AtomicInteger(0);
        final CountDownLatch sendDone = new CountDownLatch(1);
        final CountDownLatch got2Done = new CountDownLatch(1);

        // Set prefetch to 1
        connection.getPrefetchPolicy().setAll(1);
        // This test case does not work if optimized message dispatch is used as the main thread send block until the consumer receives the
        // message.  This test depends on thread decoupling so that the main thread can stop the consumer thread.
        connection.setOptimizedMessageDispatch(false);
        connection.start();

        // Use all the ack modes
        Session session = connection.createSession(false, ackMode);
        destination = createDestination(session, destinationType);
        MessageConsumer consumer = session.createConsumer(destination);
        consumer.setMessageListener(new MessageListener() {
            public void onMessage(Message m) {
                try {
                    TextMessage tm = (TextMessage)m;
                    log.info("Got in first listener: "+tm.getText());
                    assertEquals( ""+counter.get(), tm.getText() );
                    counter.incrementAndGet();
                    m.acknowledge();
                    if( counter.get()==2 ) {
                      sendDone.await();
                        connection.close();
                        got2Done.countDown();
                    }
                } catch (Throwable e) {
                    e.printStackTrace();
                }
            }
        });

        // Send the messages
        sendMessages(session, destination, 4);
        sendDone.countDown();
       
        // Wait for first 2 messages to arrive.
        assertTrue(got2Done.await(100000, TimeUnit.MILLISECONDS));

        // Re-start connection.
        connection = (ActiveMQConnection) factory.createConnection();
        connections.add(connection);
       
        connection.getPrefetchPolicy().setAll(1);
        connection.start();

        // Pickup the remaining messages.
        final CountDownLatch done2 = new CountDownLatch(1);
        session = connection.createSession(false, ackMode);
        consumer = session.createConsumer(destination);
        consumer.setMessageListener(new MessageListener() {
            public void onMessage(Message m) {
                try {
                    TextMessage tm = (TextMessage)m;
                    log.info("Got in second listener: "+tm.getText());
                    assertEquals( ""+counter.get(), tm.getText() );
                    counter.incrementAndGet();
                    if( counter.get()==4 )
                        done2.countDown();
                } catch (Throwable e) {
                    e.printStackTrace();
                }
            }
        });

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

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

        final AtomicInteger counter = new AtomicInteger(0);
        final CountDownLatch done = new CountDownLatch(1);
       
        // Receive a message with the JMS API
        connection.getPrefetchPolicy().setAll(1);
        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

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.