Reputation: 150
I am checking the ActiveMQ examples and most of them I see has been embedded with Thread. I took one of the example and removed the thread part and ran it, worked as expected. Just wondering where thread comes into picture then, or its just that more suits to the environment or something? Please help me to understand. Thanks.
Sample Code:
public class TopicConsumer implements Runnable {
ActiveMQConnectionFactory connectionFactory = null;
public TopicConsumer(ActiveMQConnectionFactory connectionFactory){
this.connectionFactory = connectionFactory;
}
@Override
public void run() {
try {
Connection connection = connectionFactory.createConnection();
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
Destination topicDestination = session.createTopic("CLIMATE");
MessageConsumer messageConsumer = session.createConsumer(topicDestination);
Message message = messageConsumer.receive();
TextMessage textMessage = (TextMessage) message;
System.out.println(textMessage.getText());
session.close();
connection.close();
} catch (JMSException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Upvotes: 1
Views: 57
Reputation: 22422
Just wondering where thread comes into picture then, or its just that more suits to the environment or something?
In general, when you place a message to jms topic, it is meant for multiple consumers, otherwise, you would have chosen a jms queue.
Your code is allowing to run multiple consumers consuming the messages parallelly from the same jms topic (note, you have hardcoded the topic name inside run()
method). It is nothing to do with the JMS environment or MQ, it is just to consume messages parallelly using multiple consumers.
You can refer the below text (emphasis mine) taken from here, which tells how a jms topic, in principle works.
In JMS a Topic implements publish and subscribe semantics. When you publish a message it goes to all the subscribers who are interested - so zero to many subscribers will receive a copy of the message.
Upvotes: 1