Skip to content
Tutorials Center
My learning

Topics

Lesson 101 of 119 ยท Architecture and Deployment

JMS and Message Queues

Learn Jakarta Messaging (JMS) - queues versus topics, durable subscriptions, selectors, acknowledgement, redelivery and dead-letter queues, request-reply, and Spring Boot listeners.

The Messaging lesson introduced asynchronous communication with RabbitMQ and Kafka, each with its own client library and its own protocol. Long before those became popular, the Java world standardized the idea: JMS, the Java Message Service, now named Jakarta Messaging (package jakarta.jms, currently version 3.1). JMS is an API, like JDBC: you write your code against the interfaces, and a provider (the broker) supplies the implementation. Apache ActiveMQ Artemis, ActiveMQ Classic, IBM MQ, Oracle AQ, TIBCO EMS and Amazon MQ all have JMS clients, and RabbitMQ and Azure Service Bus offer JMS compatibility layers.

JMS matters because a large share of enterprise Java systems (banks, insurers, logistics, telecom) still integrate through JMS brokers, and because its vocabulary (queue, topic, acknowledge, redelivery, dead-letter) is the vocabulary of messaging in general. In this lesson you will learn the JMS model, the message structure, how delivery guarantees work, and how Spring Boot makes consuming messages a one-annotation job. No broker runs in this course's code runner, so the real API appears read-only, while runnable examples model the broker's behavior in plain Java.

Where JMS fits

flowchart LR
  P1["Order service<br/>(producer)"] -->|send| Q[("Queue: orders")]
  Q -->|one consumer<br/>gets each message| C1["Worker A"]
  Q --> C2["Worker B"]
  P2["Loan service<br/>(publisher)"] -->|publish| T{{"Topic: loan-events"}}
  T -->|every subscriber<br/>gets a copy| S1["Mailer"]
  T --> S2["Statistics"]
  T --> S3["Dashboard"]

A queue distributes work; a topic broadcasts facts. The two domains are called point-to-point and publish/subscribe.

You can choose between brokers on delivery model, not just fashion. A JMS broker is a smart broker: it tracks which consumer has which message, acknowledgements, redelivery counts, expiry and priorities, and it can take part in distributed transactions (XA). Kafka by contrast is a log that consumers read at their own pace. Use JMS when you need classic work queues with per-message acknowledgement, selectors, priorities or existing enterprise brokers; use Kafka for high-volume event streams that need replay.

The JMS building blocks

Concept What it is
ConnectionFactory Created by the provider; it knows the broker address and credentials. You obtain one from configuration or JNDI.
Connection A network connection to the broker. Expensive; share it.
Session / JMSContext A single-threaded context for producing and consuming, optionally transacted. JMS 2.0's JMSContext combines connection and session in one simple object.
Destination Where messages go: a Queue or a Topic.
MessageProducer Sends messages to a destination.
MessageConsumer Receives messages, synchronously (receive) or asynchronously (a MessageListener).
Message Headers + properties + body.

A JMS message has three parts:

  • Headers, set by the provider or the client: JMSMessageID, JMSTimestamp, JMSCorrelationID, JMSReplyTo, JMSDeliveryMode, JMSPriority (0-9, default 4), JMSExpiration, JMSRedelivered, JMSType.
  • Properties, your own name/value pairs (strings, numbers, booleans), which can be used for routing with selectors.
  • Body, in one of five types: TextMessage (a string, most often JSON or XML), BytesMessage, MapMessage, StreamMessage, ObjectMessage (Java serialization; avoid it, it is a security and compatibility risk).

With the simplified API of JMS 2.0, sending and receiving a message looks like this (shown with the Artemis client; with another provider only the factory line changes):

Java
import jakarta.jms.*;
import org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory;

ConnectionFactory factory = new ActiveMQConnectionFactory("tcp://localhost:61616", "app", "secret");

try (JMSContext context = factory.createContext()) {            // closes connection and session
    Queue orders = context.createQueue("orders");

    context.createProducer()
           .setDeliveryMode(DeliveryMode.PERSISTENT)           // survive a broker restart (the default)
           .setTimeToLive(60_000)                              // expire after a minute if nobody takes it
           .setPriority(7)
           .setProperty("region", "EU")
           .send(orders, "{\"orderId\":42,\"total\":59.90}");

    String body = context.createConsumer(orders, "region = 'EU'")   // selector
                         .receiveBody(String.class, 2_000);          // wait at most 2 seconds
    System.out.println(body);
}

Key choices in that snippet:

  • Persistent messages are written to disk by the broker before send returns, so they survive a crash. Non-persistent ones are faster and may be lost; use them for data that is worthless a minute later (live prices, heartbeats).
  • Time to live keeps stale work out of the system. Expired messages go to an expiry destination instead of a consumer.
  • A selector is an SQL-92-like condition over headers and properties (region = 'EU' AND amount > 100). The broker applies it, so consumers only receive matching messages. Selectors can only read properties and headers, never the body, so put anything you want to route on into a property.

Queues, topics and durable subscriptions

Every message sent to a queue is delivered to exactly one consumer, even if many are listening: they compete. Messages wait in the queue, durably, until some consumer takes them, even if no consumer is running at the time.

A topic delivers each message to every active subscription. By default a subscription exists only while its consumer is connected, so a subscriber that is offline simply misses messages. A durable subscription makes the broker keep a copy of everything published for that subscriber while it is away and hand it over when it reconnects. A durable subscription is identified by a name (plus a client id in JMS 1.1 style), and JMS 2.0 also adds shared subscriptions, where several consumers share one subscription so they behave like competing consumers on the topic's messages.

This model implements those rules and shows the difference. (Real brokers do far more, but the delivery rules are exactly these.)

Java Queue, selector, topic and durable subscription

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Read the last block carefully. statistics was always connected and saw everything. mailer was away for two messages, yet its durable subscription collected loan-2 and loan-3. dashboard was non-durable, so it missed them, and when it resubscribed it was a brand-new subscription that only sees loan-4. Use durable subscriptions for consumers that must not lose events (billing, audit), non-durable ones for live displays.

Acknowledgement, transactions and redelivery

When has a message been "delivered"? When the broker hands it over, or when your code has finished processing it? JMS makes you choose, per session:

Mode The message is acknowledged Risk
AUTO_ACKNOWLEDGE automatically, when receive returns or when the listener returns without exception A crash while processing an already acknowledged message loses it (for receive)
CLIENT_ACKNOWLEDGE when you call message.acknowledge(), which acknowledges all messages the session has consumed so far Easy to acknowledge too much
DUPS_OK_ACKNOWLEDGE lazily, in batches The same message may be delivered twice; fastest
SESSION_TRANSACTED on session.commit(); rollback() makes the broker redeliver The safest; the usual choice

If a message is not acknowledged (the listener threw an exception, the transaction rolled back, the connection died), the broker redelivers it. The redelivered copy has JMSRedelivered = true and a delivery count (JMSXDeliveryCount). That gives JMS at-least-once delivery: a message may arrive more than once, so consumers must be idempotent (see the delivery-guarantee discussion in Messaging).

But what about a poison message, one that can never be processed (invalid JSON, a missing database row)? Redelivering it forever would block the queue and burn CPU. Brokers therefore count deliveries, and after a configured maximum (Artemis defaults to 10 attempts) they move the message to a dead-letter queue (DLQ) for humans or special tooling to inspect.

sequenceDiagram
  participant B as Broker
  participant C as Consumer
  participant D as Dead-letter queue
  B->>C: deliver msg (attempt 1)
  C--xB: exception: rollback
  B->>C: redeliver (attempt 2, JMSRedelivered=true)
  C--xB: exception: rollback
  B->>C: redeliver (attempt 3)
  C--xB: exception: rollback
  B->>D: max attempts reached: move to DLQ
  Note over D: alerts, inspection,<br/>manual replay

A transient failure usually succeeds on a later attempt. A permanent failure ends up in the dead-letter queue.

The model below runs a payment queue with a limit of three attempts. One message fails once and then works (a transient problem), one can never succeed (a poison message):

Java Redelivery and the dead-letter queue

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

In production you would not retry instantly: a delay (Artemis redelivery-delay, with a multiplier for exponential back-off) gives the failing dependency time to recover. And you would monitor the DLQ's size: a growing DLQ is an alarm, not a graveyard.

Request-reply

Messaging is asynchronous, but sometimes you want an answer. JMS has a convention for it: the requester puts a reply-to destination (JMSReplyTo) in the request, the responder sends the answer there, and copies the request's JMSMessageID into the reply's JMSCorrelationID. The requester matches replies to requests with a selector on the correlation id. This matters when many requesters share one reply queue.

Java Request-reply with correlation ids

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Request-reply over a broker couples the client to the server's availability and adds latency. Use it when the broker gives you something HTTP does not (buffering during outages, load balancing across workers); otherwise a plain REST call, as in Building a REST API, is simpler.

JMS with Spring Boot

Spring wraps the verbose parts. Add spring-boot-starter-artemis (or spring-boot-starter-activemq for ActiveMQ Classic) and configure the broker:

YAML
spring:
  artemis:
    mode: native                  # connect to an external broker ("embedded" runs one in-process)
    broker-url: tcp://localhost:61616
    user: app
    password: ${BROKER_PASSWORD}
  jms:
    template:
      default-destination: orders

Sending uses JmsTemplate; Spring converts objects to JSON when a MessageConverter bean is present:

Java
@Configuration
class JmsConfig {
    @Bean
    MessageConverter jacksonJmsMessageConverter() {
        MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter();
        converter.setTargetType(MessageType.TEXT);
        converter.setTypeIdPropertyName("_type");           // tells the receiver which class to build
        return converter;
    }
}

@Service
class OrderPublisher {
    private final JmsTemplate jms;

    OrderPublisher(JmsTemplate jms) {
        this.jms = jms;
    }

    void publish(OrderPlaced order) {
        jms.convertAndSend("orders", order, message -> {
            message.setStringProperty("region", order.region());     // available to selectors
            return message;
        });
    }
}

(In Spring Framework 7 with Jackson 3 the converter class is named JacksonJsonMessageConverter; the idea is the same.)

Receiving uses @JmsListener. Spring Boot's default listener container is session-transacted when no other transaction manager is configured, so an exception thrown from the method rolls back and the broker redelivers it, exactly the behavior of the model above:

Java
@Component
class OrderListener {

    @JmsListener(destination = "orders", concurrency = "3-10", selector = "region = 'EU'")
    void onOrder(OrderPlaced order) {
        shipments.create(order);          // throw to roll back and get a redelivery
    }
}

concurrency = "3-10" lets the container scale between 3 and 10 consumer threads according to load: competing consumers. For a topic, a separate container factory switches the domain and makes the subscription durable:

Java
@Bean
DefaultJmsListenerContainerFactory topicFactory(ConnectionFactory connectionFactory,
                                                DefaultJmsListenerContainerFactoryConfigurer configurer) {
    DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory();
    configurer.configure(factory, connectionFactory);
    factory.setPubSubDomain(true);                 // topics instead of queues
    factory.setSubscriptionDurable(true);
    factory.setClientId("mailer-service");
    return factory;
}

@JmsListener(destination = "loan-events", containerFactory = "topicFactory", subscription = "mailer")
void onLoanEvent(LoanCreated event) { ... }

A listener can also answer: annotate it with @SendTo("price-replies") and return a value, and Spring sends the return value to that destination, copying the correlation id for you. JmsTemplate.sendAndReceive is the matching client side.

Configure the dead-letter handling on the broker, not in each consumer. In Artemis this is an address-setting with max-delivery-attempts, redelivery-delay and dead-letter-address. Then write a small tool or listener that reads the DLQ, so poison messages are visible and can be replayed after the bug is fixed.

Practical rules

  • Keep messages small and self-describing. Send ids and facts, not entire database graphs. Include a type or version property.
  • Make consumers idempotent. At-least-once delivery means duplicates will happen. Store a processed-message id, or make the operation naturally repeatable.
  • Don't send the same logical change both to the database and to the broker without care. If the commit and the send can diverge, use the transactional outbox described in Messaging.
  • Order is limited. JMS guarantees order only for messages from one producer session to one destination with the same priority and delivery mode, and parallel consumers destroy processing order. Use one consumer, or message groups on the broker, when order matters.
  • Never use ObjectMessage across systems. Use JSON or another explicit format.
  • Monitor queue depth, consumer count, redelivery counts and the DLQ. A queue that only grows means consumers are too slow or down.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Three workers listen on the same queue and ten messages are sent. How many times is each message processed?

    A queue delivers each message to exactly one consumer. The workers compete, which spreads the work.
  2. 2. A subscriber of a topic is offline while three events are published. When does it receive them after reconnecting?

    A durable subscription makes the broker keep a copy for the named subscriber. Non-durable subscriptions exist only while connected.
  3. 3. A listener throws an exception while processing a message in a transacted session. What happens?

    Rollback means the message was not acknowledged. The broker counts deliveries and, past the maximum, parks the message in the dead-letter queue.
  4. 4. Why should JMS consumers be idempotent?

    Redelivery after a failure or lost acknowledgement can create duplicates. The consumer must tolerate seeing a message again.
  5. 5. Which statement about selectors is true?

    Selectors are SQL-like conditions over headers and properties, evaluated by the broker. The body is opaque to them.

Summary

  • JMS (Jakarta Messaging) is the standard Java API for messaging; a provider such as ActiveMQ Artemis or IBM MQ implements it.
  • Queues deliver each message to one consumer (work distribution); topics deliver to every subscription. Durable subscriptions keep messages for offline subscribers.
  • A message has headers, properties (usable in selectors) and a body; prefer text (JSON) bodies and avoid ObjectMessage.
  • Acknowledgement modes and transacted sessions decide when a message counts as done. Failures cause redelivery; after the maximum attempts, poison messages go to a dead-letter queue.
  • Delivery is at-least-once, so make consumers idempotent. Ordering is limited.
  • Request-reply uses JMSReplyTo and JMSCorrelationID.
  • Spring Boot offers JmsTemplate for sending and @JmsListener for receiving, with concurrency ranges, selectors and topic factories.

Next: Deploying Java to Kubernetes shows how to run these services in a cluster with proper probes, resource limits and configuration.