Reputation: 3733
I have a basic doubt about rabbitMQ. I read a sample program in https://www.rabbitmq.com/tutorials/tutorial-two-java.html
public class Recv {
private final static String QUEUE_NAME = "hello";
public static void main(String[] argv) throws Exception {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
**Connection connection = factory.newConnection();
Channel channel = connection.createChannel()**;
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
System.out.println(" [*] Waiting for messages. To exit press CTRL+C");
}
}
It says that we should not use a try-with-resource statement to automatically close the channel and the connection but instead we should write as it is given.
But my doubt is why the program is not exiting after executing System.out.println(" [*] Waiting for messages. To exit press CTRL+C");, I could not see a wait/while loop in the code.
I know that I am missing some basic info but I could not find out that yet.
Upvotes: 0
Views: 208
Reputation: 315
The Program did not close automatically as RabbitMQ is running tasks Asynchronously.
The Connection
and Channel
are open.
It's because we did not use "try-with-resource statement". Without it, we need to close connection and channel manually.
Quoting the Page you mentioned: RabbitMQ Tutorial 1: Java
In case of a Publisher:
We can use a try-with-resources statement because both
Connection
andChannel
implementjava.io.Closeable
. This way we don't need to close them explicitly in our code
Receiver(Applies to class in Question here):
Why don't we use a try-with-resource statement to automatically close the channel and the connection? By doing so we would simply make the program move on, close everything, and exit! This would be awkward because we want the process to stay alive while the consumer is listening asynchronously for messages to arrive.
Edit: Adding reference for my comment on this answer: java-daemon-thread
Upvotes: 1