JMSMessageID example

In this post under JMS, I will explain about JMSMessageID with an example

JMSMessageID is a header field which is only set by JMS Provider and contains a string value that uniquely identifies a message.

JMSMessageID is set by the provider when the JMSProducer calls the send method.

Before calling the JMSProducer’s send method, the value will be null or provider specific value such as “ID:0-” denoting no value, but after calling the send method, the value will be there.

All JMSMessageID values must start with prefix “ID:”.

Below is Producer class example which shows the usage of JMSMessageID.


1  package package11;
3  import javax.jms.ConnectionFactory;
4  import javax.jms.Destination;
5  import javax.jms.JMSContext;
6  import javax.jms.JMSProducer;
7  import javax.jms.Message;
9  public class Producer implements Runnable {
10 	private Destination destination;
11 	private ConnectionFactory connectionFactory;
13 	public Producer(Destination destination, ConnectionFactory connectionFactory) {
14 		this.destination = destination;
15 		this.connectionFactory = connectionFactory;
16 	}
18 	@Override
19 	public void run() {
20 		JMSContext jmsContext =  null;
22 		try {
23 			jmsContext = connectionFactory.createContext();
24 			Message message = jmsContext.createTextMessage("Hello World1");
25 			JMSProducer jmsProducer = jmsContext.createProducer();
26 			System.out.println("Before sending JMSMessageID: " + message.getJMSMessageID());
27 			jmsProducer.send(destination, message);
28 			System.out.println("After sending JMSMessageID: " + message.getJMSMessageID());
29 		} catch(Exception excep) {
30 			excep.printStackTrace();
31 		} finally {
32 			if(jmsContext != null) {
33 				jmsContext.close();
34 			}
35 		}
36 	}
37 }

In the above code, at line 26, we are retrieving the value of JMSMessageID before calling the send method. As a result the value will be “ID:0-”

At line 28, we are again retrieving the value of JMSMessageID but this time after calling the send method. As a result the value will be there or other than “ID:0-”.

Below is the output


Before sending JMSMessageID: ID:0-
After sending JMSMessageID: ID:13-

Creating a JMSMessageID is time consuming and increases message size. We can instruct the JMS Provider to not generate unique id by calling “setDisableMessageID” method. This works only if JMS Provider does not ignore the setting “setDisableMessageID”. If JMS Provider doesn’t ignore then the value of message id will always be null or “ID:0-”.

Leave a Reply