Search code examples
springjmsactivemq-classicproducer-consumer

Getting Compile time error while implementing MessageCreator in ActiveMq


I am trying to get into ActiveMq and following the tutorial on the below link:

Spring-ActiveMq Example

While creating ActiveMQMessageProducer class i am getting compile time error for the following line:

textMessage.setIntProperty(MSG_COUNT, messageCount);

Error is

"Cannot refer to the non-final local variable messageCount defined in an enclosing scope"

What i am not getting is that how it's working according to tutorial.

Thanks


Solution

  • There's a bug in this tutorial because the method of the inner anonymous class cannot refer to a non-final variable. Here's a fixed version:

       public void generateMessages() throws JMSException 
    {
        for (int messageCount = 0; messageCount < 10; messageCount++) 
        {
            final String text = "TP Message " + messageCount;
            final int count = messageCount; // copy the value into a final
            jmsTemplate.send(new MessageCreator() 
            {
                public Message createMessage(Session session) throws JMSException
                {
                    TextMessage textMessage = session.createTextMessage(text);
                    textMessage.setIntProperty(MSG_COUNT, count); // use it             
                    return textMessage;
                }
            });
        }
    }