Messaging & Event Streaming

The JMS API (Jakarta Messaging 3.1): Sessions, Messages, Acknowledgement and Selectors

Intermediate8 min readUpdated

Jakarta Messaging (JMS) is the standard Java API for talking to a message broker. This guide walks through the classic and simplified APIs, the message types and headers you will use, what each acknowledgement mode really promises, how selectors and durable or shared subscriptions work, and how to build request-reply on top of queues — with runnable examples against ActiveMQ Classic 6.

What you will learn

  • Set up a JMS 3.1 client with a ConnectionFactory and send and receive messages with JMSContext
  • Choose the right message type and use headers and properties correctly
  • Explain what AUTO, CLIENT, DUPS_OK and transacted acknowledgement modes guarantee
  • Filter messages with selectors and consume topics through durable and shared subscriptions
  • Implement request-reply with temporary queues and correlation identifiers
  • Use JmsTemplate and @JmsListener in Spring instead of the raw API

Jakarta Messaging — still universally called JMS — is the API a Java application uses to send messages to and receive messages from a broker. The API is a contract, not a product: ActiveMQ Classic, ActiveMQ Artemis, IBM MQ, Oracle AQ and many others provide implementations, and code that sticks to jakarta.jms interfaces moves between them with configuration changes only. This guide targets JMS 3.1 (Jakarta EE 10) and uses ActiveMQ Classic 6 as the broker for examples, because it is small and free to run locally.

Two APIs, one model

JMS has carried two programming styles since version 2.0.

The classic API (JMS 1.1) builds a chain of objects: a ConnectionFactory creates a Connection, the connection creates a Session, the session creates MessageProducer, MessageConsumer and Message objects. It is verbose but explicit, and it is what application servers use under the hood for message-driven beans.

The simplified API (JMS 2.0 onward) folds connection and session into one JMSContext and gives it fluent JMSProducer and JMSConsumer helpers. Everything the classic API can do, the simplified API can do in fewer lines and with AutoCloseable resources. Use it for new code.

Both styles share the same objects underneath, and every concept below — destinations, message types, acknowledgement, selectors — applies to both.

Add the API and a broker client to the project. The API artifact provides the interfaces; the client artifact provides the implementation:

<dependency>
  <groupId>jakarta.jms</groupId>
  <artifactId>jakarta.jms-api</artifactId>
  <version>3.1.0</version>
</dependency>
<dependency>
  <groupId>org.apache.activemq</groupId>
  <artifactId>activemq-client</artifactId>
  <version>6.1.6</version> <!-- any 6.x: Jakarta namespace, Java 17+ -->
</dependency>

Sending a message

The ConnectionFactory is the only vendor-specific object you touch. In a standalone application you construct it; in an application server you look it up through JNDI or inject it with @Resource.

import jakarta.jms.ConnectionFactory;
import jakarta.jms.JMSContext;
import jakarta.jms.Queue;
import org.apache.activemq.ActiveMQConnectionFactory;

public class OrderSender {
  public static void main(String[] args) {
    ConnectionFactory factory = new ActiveMQConnectionFactory("tcp://localhost:61616");

    // JMSContext = Connection + Session; try-with-resources closes both
    try (JMSContext context = factory.createContext()) {
      Queue orders = context.createQueue("orders.placed");
      context.createProducer()
          .setProperty("eventType", "OrderPlaced")   // filterable by selectors
          .setProperty("schemaVersion", 2)
          .setTimeToLive(60_000)                     // expire after 60 s if unconsumed
          .send(orders, "{\"orderId\":\"o-9911\",\"total\":149.90}");
    }
  }
}

createContext() without arguments gives AUTO_ACKNOWLEDGE mode; createContext(JMSContext.SESSION_TRANSACTED) gives a transacted context you must commit(). createQueue("orders.placed") does not create anything on the broker: it builds a client-side identity for a destination. ActiveMQ Classic creates the queue on first use; other brokers require an administrator to define it first, which is why the specification treats destinations as administered objects normally obtained from JNDI.

The JMSProducer returned by createProducer() is lightweight and reusable; set delivery mode, priority, time to live and properties on it, then call send as many times as you need.

Receiving a message

Consumers come in two shapes: blocking calls to receive, and asynchronous MessageListener callbacks.

try (JMSContext context = factory.createContext()) {
  JMSConsumer consumer = context.createConsumer(context.createQueue("orders.placed"));

  // Blocking receive with a timeout; returns null if nothing arrives in 5 s
  Message message = consumer.receive(5_000);
  if (message != null) {
    String body = message.getBody(String.class);   // JMS 2.0 typed body access
    System.out.println("received " + body);
  }
}

The asynchronous form registers a listener; the client library calls onMessage on its own thread for each delivery:

JMSContext context = factory.createContext();          // keep open for the listener's lifetime
JMSConsumer consumer = context.createConsumer(context.createQueue("orders.placed"));
consumer.setMessageListener(message -> {
  try {
    process(message.getBody(String.class));
  } catch (JMSException e) {
    throw new RuntimeException(e);                     // makes the broker redeliver
  }
});

Two rules matter here. A session (and therefore a JMSContext) is single-threaded: never share it between threads or call it from inside a listener that belongs to it. And the connection must be started before consumers receive anything — JMSContext does this automatically, whereas the classic API requires an explicit connection.start(), which is the single most common cause of "my consumer receives nothing".

Message types, headers and properties

A JMS message is headers plus properties plus a typed body. Choose the body type by what the consumer needs to do with it.

TypeBodyUse it for
TextMessageStringJSON, XML, plain text — the default choice
BytesMessageraw bytesFiles, Protocol Buffers, anything already serialised
MapMessagename → primitive/StringSimple structured data without a schema library
ObjectMessageSerializable objectAvoid: couples both sides to a Java class and is a deserialisation attack surface
StreamMessagesequence of primitivesRare; read in the same order as written
MessagenonePure signal, all information in properties

Headers are fixed fields defined by the specification. The producer sets some (JMSDeliveryMode, JMSPriority, JMSExpiration through time-to-live, JMSReplyTo, JMSCorrelationID, JMSType, and since JMS 2.0 JMSDeliveryTime for scheduled delivery); the provider sets the rest (JMSMessageID, JMSTimestamp, JMSDestination, JMSRedelivered). Priority ranges from 0 to 9 with 4 as the default, and brokers are only required to try to deliver higher priorities first.

Properties are your own key-value pairs, typed as boolean, numeric or String. Properties whose names start with JMSX are reserved: JMSXGroupID and JMSXGroupSeq group related messages so that one consumer sees a whole sequence in order, and JMSXDeliveryCount (mandatory since 2.0) tells a consumer how many times it has seen this message — the basis for poison-message handling.

TextMessage message = context.createTextMessage(json);
message.setStringProperty("eventType", "OrderPlaced");
message.setStringProperty("JMSXGroupID", "customer-4711");   // keep one customer's messages ordered
message.setJMSType("order");                                  // free-form type hint, rarely used

Delivery mode deserves a sentence of its own. DeliveryMode.PERSISTENT (the default) tells the broker to write the message to its store before acknowledging the send, so the message survives a broker restart; the producer blocks until that acknowledgement arrives. NON_PERSISTENT skips the disk and the wait, which is several times faster and appropriate for metrics, heartbeats and anything you can afford to lose.

Acknowledgement modes: what is really promised

A message stays in the queue until the consumer acknowledges it. How that acknowledgement happens is the acknowledgement mode of the session, and it decides your delivery guarantee.

ModeAcknowledgement sent whenGuaranteeDuplicate risk
AUTO_ACKNOWLEDGEreceive() returns or onMessage returns normallyAt-least-onceCrash between processing and return
CLIENT_ACKNOWLEDGEYou call message.acknowledge() (acknowledges all messages consumed so far in the session)At-least-once, under your controlAnything you have not acknowledged
DUPS_OK_ACKNOWLEDGELazily, in batches, at the provider's discretionAt-least-once with more duplicates, lower overheadWhole batch after a crash
SESSION_TRANSACTEDOn commit(); rollback() returns messages for redeliveryAtomic consume-and-produceEverything since the last commit

Two subtleties bite people. First, CLIENT_ACKNOWLEDGE is session-wide: acknowledging message 5 also acknowledges 1 to 4, so it is not a per-message tool (ActiveMQ offers a non-standard INDIVIDUAL_ACKNOWLEDGE for that). Second, a transacted session groups sends and receives: consuming from orders.placed and sending to invoices.created in one transaction means both happen or neither does, as far as the broker is concerned. It does not include your database — for that you need an XA transaction manager through an application server, or the outbox pattern.

try (JMSContext context = factory.createContext(JMSContext.SESSION_TRANSACTED)) {
  JMSConsumer consumer = context.createConsumer(context.createQueue("orders.placed"));
  JMSProducer producer = context.createProducer();
  Message order = consumer.receive();
  try {
    String invoice = createInvoice(order.getBody(String.class));
    producer.send(context.createQueue("invoices.created"), invoice);
    context.commit();          // order removed, invoice visible — atomically
  } catch (RuntimeException e) {
    context.rollback();        // order redelivered, invoice never sent
  }
}

When redelivery happens, the broker sets JMSRedelivered and increments JMSXDeliveryCount. ActiveMQ's client applies a redelivery policy (six attempts with a one-second delay by default) and then sends the message to a dead-letter queue named ActiveMQ.DLQ; check that queue whenever messages "disappear".

Selectors

A message selector lets a consumer receive only the messages whose headers or properties match an expression. The syntax is a subset of SQL-92 WHERE clauses, evaluated by the broker so that non-matching messages are never sent over the wire to that consumer.

JMSConsumer highValue = context.createConsumer(
    context.createQueue("orders.placed"),
    "eventType = 'OrderPlaced' AND total > 1000 AND region IN ('EU', 'UK')");

Supported operators include comparison, AND/OR/NOT, BETWEEN, IN, LIKE with % and _ wildcards, IS NULL, and arithmetic. Identifiers refer to property names or the JMS-prefixed headers that are selectable (JMSDeliveryMode, JMSPriority, JMSMessageID, JMSTimestamp, JMSCorrelationID, JMSType). Selectors on queues have a cost: a queue whose only consumers use selectors that match nothing accumulates unmatched messages forever. On topics they are free, because non-matching messages are simply not delivered to that subscription.

Topics: durable and shared subscriptions

A plain topic consumer receives messages published while it is connected and nothing else. Two subscription types change that.

A durable subscription is identified by a name (and, in the classic API, a client identifier). The broker keeps messages for it while the subscriber is offline and delivers the backlog on reconnection:

JMSConsumer audit = context.createDurableConsumer(
    context.createTopic("customer.events"), "audit-service");

Until JMS 2.0, a durable subscription allowed exactly one active consumer, which made scaling a topic consumer impossible without provider-specific tricks such as ActiveMQ's virtual topics. Shared subscriptions fix that: several consumers using the same shared subscription name divide the messages between them, queue-style.

// Three instances of the same service can each call this; messages are load-balanced
JMSConsumer worker = context.createSharedDurableConsumer(
    context.createTopic("customer.events"), "email-service");

Use createSharedConsumer when the subscription need not survive disconnection and createSharedDurableConsumer when it must. Remember to unsubscribe(name) when a durable subscription is decommissioned; otherwise the broker stores messages for a subscriber that will never return, and the disk fills up.

Request-reply over queues

JMS has no built-in remote-call primitive, but the headers make a robust one easy. The requester creates a temporary queue (a destination that exists only for the life of its connection), sends the request with JMSReplyTo pointing at it and a fresh JMSCorrelationID, then waits for a reply whose correlation identifier matches.

try (JMSContext context = factory.createContext()) {
  TemporaryQueue replies = context.createTemporaryQueue();
  String correlationId = UUID.randomUUID().toString();

  context.createProducer()
      .setJMSReplyTo(replies)
      .setJMSCorrelationID(correlationId)
      .send(context.createQueue("pricing.requests"), "{\"sku\":\"A-100\"}");

  // Selector ensures we only pick up our own answer if the temp queue is shared
  Message reply = context.createConsumer(replies, "JMSCorrelationID = '" + correlationId + "'")
      .receive(2_000);
  if (reply == null) throw new IllegalStateException("pricing service did not answer in time");
}

The responder reads getJMSReplyTo() and getJMSCorrelationID() from the request and sends its answer to that destination with the same correlation identifier. Give every request a timeout: a waiting requester with no timeout is a thread leak waiting for a broker hiccup.

JMS in Spring: JmsTemplate and @JmsListener

Most Java teams never call the raw API, because Spring's JmsTemplate handles connection, session and resource cleanup, and @JmsListener turns any method into a consumer backed by a pool of listener threads. With Spring Boot 3.2 or later, spring-boot-starter-activemq auto-configures a ConnectionFactory from spring.activemq.broker-url and wraps it in a caching factory so that every send does not open a new TCP connection.

@Service
public class OrderEvents {
  private final JmsTemplate jms;
  OrderEvents(JmsTemplate jms) { this.jms = jms; }

  public void orderPlaced(String json) {
    jms.convertAndSend("orders.placed", json, m -> {
      m.setStringProperty("eventType", "OrderPlaced");
      return m;
    });
  }
}

@Component
public class OrderConsumer {
  @JmsListener(destination = "orders.placed", selector = "eventType = 'OrderPlaced'", concurrency = "3-10")
  public void handle(String json, @Header("JMSXDeliveryCount") int attempt) {
    // throwing here rolls back / rejects the message and triggers redelivery
  }
}

Set spring.jms.listener.session.transacted=true (the Boot default for the listener container) so that an exception in a listener method rolls the message back rather than losing it, and set spring.jms.pub-sub-domain=true only if the destination names refer to topics.

Common mistakes

  • Forgetting connection.start() with the classic API. The consumer connects, the queue has messages, nothing arrives. JMSContext starts the connection lazily on first consumer creation, which is one reason to prefer it.
  • Creating a connection per message. Connections are expensive TCP sessions with their own threads. Create one ConnectionFactory and a small number of long-lived connections; in Spring, use CachingConnectionFactory or the Boot default.
  • Sharing a session across threads. Sessions are not thread-safe. Each worker thread gets its own session (or JMSContext); share the connection, not the session.
  • Using ObjectMessage. It forces both sides to have the same class on the classpath and invites Java deserialisation vulnerabilities. Send JSON in a TextMessage; use the JSON formatter to inspect payloads while debugging.
  • Selectors that never match on a queue. The messages pile up. Either route to different queues at send time or make sure some consumer matches everything.
  • Ignoring the dead-letter queue. Poison messages end up in ActiveMQ.DLQ (or your provider's equivalent) silently. Monitor it and build a way to inspect and replay its contents.

Key takeaways

  • JMS is an API; the broker client you add to the classpath decides which wire protocol is used and which broker you can reach.
  • Prefer JMSContext and try-with-resources; keep sessions single-threaded and connections long-lived.
  • Send JSON in TextMessage, put routing metadata in properties, and use JMSXGroupID when a set of messages must stay in order.
  • Acknowledgement mode defines your guarantee: AUTO and CLIENT give at-least-once, DUPS_OK trades duplicates for speed, and transacted sessions make consume-plus-produce atomic on the broker.
  • Selectors filter on headers and properties only; shared durable subscriptions let you scale topic consumers like a queue.
  • Request-reply is temporary queue plus JMSReplyTo plus JMSCorrelationID, always with a timeout.
  • In Spring, JmsTemplate and @JmsListener remove the boilerplate without changing any of the guarantees above.

Sources and further reading

Frequently asked questions

What changed between javax.jms and jakarta.jms?
The package name and nothing else that affects most code. Jakarta Messaging 3.0 moved the API from javax.jms to jakarta.jms as part of the Jakarta EE 9 namespace change; 3.1 (Jakarta EE 10) made minor clarifications. Brokers ship separate client artifacts for each namespace — ActiveMQ Classic 6 uses jakarta.jms, 5.x uses javax.jms — so pick the client that matches your application server or Spring Boot version.
Should I use JMSContext or the classic Connection/Session API?
Use JMSContext (the simplified API from JMS 2.0) for new code: one object replaces Connection and Session, methods chain, and try-with-resources closes everything. The classic API is still needed when you work with older frameworks, XA transactions through an application server, or code that must run on a JMS 1.1 broker.
Does AUTO_ACKNOWLEDGE mean a message can never be lost?
It means the message is acknowledged once your MessageListener's onMessage returns or your receive() call returns. If your process crashes inside onMessage the message is redelivered, so you get at-least-once behaviour. If you hand the message to another thread and return immediately, the acknowledgement is sent before the work is done, and a crash then loses it.
Can a selector filter on the message body?
No. Selectors are evaluated by the broker against headers and properties only, using a subset of SQL-92 syntax. Put any field you want to filter on in a message property when you send it.