I have the following code. I m trying to access a queue and consume resources, well i dont know how many elements are in the queue and how many left, so i am doing while(true) but in this case, i cant close the connection which causes errors, later on, like the process doesnt die. even though i stopped it.
How can i find if there are more items in the queue then do the following ? i looked at ActiveMqQueueBrowser but it s internal so i cant really use it easily.
What would you do? What do u recommend?
ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(url);
Connection connection = connectionFactory.createConnection();
connection.start();
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
Destination destination = session.createQueue(subject);
MessageConsumer consumer = session.createConsumer(destination);
while(true){
Message message = consumer.receive();
if (message instanceof TextMessage) {
TextMessage textMessage = (TextMessage) message;
System.out.println("message from queue : '" + textMessage.getText() + "'");
}
}
// unreachable code. compiler complains.
// connection.close();
Sounds like you need to have another thread. How do you know when to be done listening? If its where the consumerQueue no longer has a value, try this:
Otherwise you are right, the loop will never return and you won;t be able to close the connections correctly when the JVM comes down.