Java EE / Jakarta EE
Message-Driven Beans and Jakarta Messaging (JMS 3.1) in the Container
Intermediate9 min readUpdated
Message-driven beans are the container's way of consuming Jakarta Messaging (JMS) messages: you write one onMessage method and the server handles connections, threads, transactions and redelivery. This guide explains how an MDB is activated and configured, how sending works from a session bean with the simplified JMS 2.0+ API, how container transactions interact with acknowledgement and redelivery, and how to avoid poison messages, lost ordering and duplicate processing.
What you will learn
- Write and configure a message-driven bean with activation properties for a queue or a topic
- Send messages from container code using an injected JMSContext and resource definitions
- Explain how container-managed transactions drive acknowledgement, rollback and redelivery
- Use selectors, durable and shared subscriptions, and control MDB concurrency
- Design consumers that tolerate duplicates and poison messages
Most of the messaging knowledge you need — why queues decouple systems, what a broker guarantees, how topics differ from queues — is independent of Jakarta EE and is covered in the messaging subject. What the platform adds is a way to consume and produce messages without managing connections, sessions, threads or acknowledgements yourself: the message-driven bean on the consuming side and an injected JMSContext on the producing side, both wired into the container's transaction manager. That integration is powerful and also the source of most surprises, so this guide concentrates on how the container behaves rather than on the API surface.
The consumer side: message-driven beans
A message-driven bean (MDB) is a class annotated with @MessageDriven that implements jakarta.jms.MessageListener. The container connects to the broker on your behalf, creates a pool of instances, and calls onMessage on a pooled instance for each message that arrives.
package shop.messaging;
import jakarta.ejb.ActivationConfigProperty;
import jakarta.ejb.MessageDriven;
import jakarta.inject.Inject;
import jakarta.jms.JMSException;
import jakarta.jms.Message;
import jakarta.jms.MessageListener;
import jakarta.jms.TextMessage;
@MessageDriven(activationConfig = {
@ActivationConfigProperty(propertyName = "destinationLookup", propertyValue = "java:/jms/queue/orders"),
@ActivationConfigProperty(propertyName = "destinationType", propertyValue = "jakarta.jms.Queue"),
@ActivationConfigProperty(propertyName = "messageSelector", propertyValue = "region = 'EU'")
})
public class OrderPlacedListener implements MessageListener {
@Inject
OrderProcessor processor; // the business logic lives in a testable bean
@Override
public void onMessage(Message message) {
try {
String payload = message.getBody(String.class); // JMS 2.0+: typed body access
String orderId = message.getStringProperty("orderId");
processor.process(orderId, payload);
} catch (JMSException e) {
throw new IllegalStateException("cannot read message", e); // roll back and redeliver
}
}
}
onMessage has no return value and no checked exceptions; the only way to signal failure is to throw a runtime exception or mark the transaction for rollback. The activation configuration tells the container what to consume. The properties defined by the Messaging specification are:
| Property | Meaning |
|---|---|
destinationLookup | JNDI name of the queue or topic |
destinationType | jakarta.jms.Queue or jakarta.jms.Topic |
connectionFactoryLookup | JNDI name of the connection factory; the server's default if omitted |
messageSelector | SQL-92-style filter on headers and properties, evaluated by the broker |
acknowledgeMode | Auto-acknowledge or Dups-ok-acknowledge; only relevant with bean-managed transactions |
subscriptionDurability | Durable or NonDurable for topics |
subscriptionName, clientId | Identify a durable subscription |
Anything else — pool size, redelivery delay, batch size — is a vendor property of the resource adapter that connects the server to the broker. That matters: an MDB is, formally, an endpoint of the Jakarta Connectors architecture, and the same annotation works with adapters for non-JMS systems (mail, files, Kafka) as long as you implement the adapter's listener interface instead of MessageListener. When a server has more than one adapter, the one an MDB uses is selected by the server's defaults or named in the vendor deployment descriptor (for example jboss-ejb3.xml on WildFly).
Destinations are best defined in the server, but for tests and self-contained deployments you can declare them in code:
@JMSDestinationDefinition(
name = "java:/jms/queue/orders",
interfaceName = "jakarta.jms.Queue",
destinationName = "orders")
@JMSConnectionFactoryDefinition(
name = "java:/jms/OrdersCF",
transactional = true)
@ApplicationScoped
public class MessagingResources { }
The producer side: JMSContext
JMS 1.1 required a Connection, a Session, a MessageProducer and a try/finally to close them all. JMS 2.0 (Java EE 7) introduced the simplified API: JMSContext wraps connection and session, JMSProducer is a fluent builder, and inside a container you inject the context and never close it.
import jakarta.annotation.Resource;
import jakarta.ejb.Stateless;
import jakarta.inject.Inject;
import jakarta.jms.*;
@Stateless
public class OrderPublisher {
@Inject
@JMSConnectionFactory("java:/jms/OrdersCF") // optional; default factory if omitted
JMSContext context; // container-managed, scoped to the transaction
@Resource(lookup = "java:/jms/queue/orders")
Queue orders;
public void orderPlaced(Order order) {
context.createProducer()
.setProperty("orderId", order.getId().toString())
.setProperty("region", order.getRegion())
.setDeliveryMode(DeliveryMode.PERSISTENT)
.setTimeToLive(24 * 60 * 60 * 1000L)
.send(orders, toJson(order)); // send(Destination, String) creates a TextMessage
}
}
The injected JMSContext is transaction-scoped: when the session bean's JTA transaction commits, the message is delivered; when it rolls back, the message is discarded. If the same method also writes to a database through JPA, both happen atomically — provided the connection factory is XA-capable and the transaction manager coordinates both resources, which is the subject of the transactions guide. Outside a transaction the context behaves as an auto-acknowledge session and messages leave immediately.
For message bodies, prefer TextMessage with JSON or BytesMessage with a documented encoding. ObjectMessage with Java serialisation ties producer and consumer to the same class versions and is a deserialisation-attack vector; brokers and servers increasingly block it by default. MapMessage is fine for small, flat payloads.
How transactions drive acknowledgement
This is the part that trips up developers who learned JMS outside a container. In a stand-alone client you choose an acknowledgement mode — auto, client or dups-ok — or a transacted session, and you call acknowledge() or commit() yourself. In an MDB with container-managed transactions, the default, none of that applies:
- The container receives the message and starts a JTA transaction.
- It enlists the JMS session in that transaction and calls
onMessage. - Any JPA work, other JMS sends or JDBC calls in the method are enlisted too.
- If
onMessagereturns normally, the container commits: the database changes are written, outgoing messages are released, and the incoming message is acknowledged — all together. - If
onMessagethrows a runtime exception or callsmessageDrivenContext.setRollbackOnly(), everything rolls back and the broker redelivers the message, withJMSRedeliveredset to true andJMSXDeliveryCountincremented.
The MDB's transaction attribute can be REQUIRED (the default) or NOT_SUPPORTED; the other attributes make no sense because there is no calling transaction to join. With @TransactionManagement(BEAN) the message is acknowledged according to acknowledgeMode when onMessage returns, regardless of what your UserTransaction did — so a bean-managed MDB can commit its database work and still lose the acknowledgement, or acknowledge a message whose processing failed. Stay with container-managed transactions unless you have a specific reason.
Queues, topics and subscriptions
A queue delivers each message to one consumer; a topic delivers each message to every subscriber. Two details of topic consumption are specific to the container:
- A durable subscription survives the MDB being undeployed or the server being down: the broker keeps the messages until the subscriber returns. It is identified by
clientIdplussubscriptionName, and a JMS 1.1-style durable subscription can have only one active consumer. That collides with an MDB pool, which is why JMS 2.0 added shared subscriptions to the API (createSharedDurableConsumer); whether an MDB pool uses one is a vendor activation property (WildFly's Artemis adapter calls itshareSubscriptions), and with it several instances — even on several cluster nodes — share one durable subscription. - A non-durable topic subscription loses messages published while the MDB is not running. That is fine for cache-invalidation broadcasts and wrong for anything business-critical.
Message selectors let a consumer receive a subset of a destination's messages based on headers and properties (region = 'EU' AND priority > 4). They are evaluated by the broker, so unmatched messages are never sent to the consumer — but on a queue they are also never consumed by this consumer, and if no consumer matches them they sit there forever. Use selectors on topics freely and on queues only when every message is guaranteed a matching consumer.
Concurrency, pooling and ordering
The container runs several MDB instances concurrently — WildFly's default pool for MDBs and Open Liberty's maxConcurrency are typical knobs — and each instance receives messages independently. Concurrency is why MDBs scale, and it has two consequences:
- Ordering is not preserved across instances. Two messages for the same order may be processed in parallel and complete in the wrong sequence. Set the pool size to one for strict ordering, use broker message groups (ActiveMQ Artemis
JMSXGroupID) to pin a key to one consumer, or make handlers order-independent by carrying a version or timestamp in the message. - A slow
onMessageblocks a pool slot. Long-running work inside an MDB starves other messages; if processing is slow, acknowledge fast by handing the work to a queue of its own or a managed executor within the transaction boundaries you can accept.
Instances are stateless from the container's point of view: like stateless session beans, they are pooled, and instance fields must hold only injected resources.
Designing a robust consumer
Because redelivery exists, every consumer must be idempotent: processing the same message twice must have the same effect as processing it once. Practical techniques, from cheapest to strongest:
- Make the operation naturally idempotent — set a status rather than incrementing a counter.
- Store the
JMSMessageID(or a business key carried as a property) in the same database transaction as the effect, with a unique constraint; a duplicate then fails the insert and you commit without doing the work again. - For external side effects that cannot be rolled back — sending e-mail, calling a payment API — record intent in the database first and perform the side effect from a separate consumer that checks the record.
Validate the message before touching any resource, and send messages that can never be processed (bad schema, unknown type) to an error queue with the reason in a property, then return normally so the broker does not keep redelivering. Log the JMSMessageID and the correlation id on every line; when a message is stuck in redelivery, that id is how you find it in the broker console. And keep the MDB thin — parsing plus a call to a service bean — so the logic can be tested with a plain JUnit test and the MDB tested once with an embedded broker.
What Jakarta Messaging 3.1 does and does not change
Messaging 3.0 was the namespace change (javax.jms to jakarta.jms); 3.1, part of Jakarta EE 10, raised the Java baseline and made small clarifications but added no new API. The long-discussed next generation — CDI-native listeners on ordinary beans, a reactive API — has not shipped, so the MDB remains the only standard, portable way to consume messages in a Jakarta EE server. Vendors fill the gap: WildFly and Open Liberty expose Artemis and their own engine features through activation properties, and MicroProfile Reactive Messaging offers an annotation-driven alternative on runtimes that support it. When you read code using javax.jms, @MessageDriven from javax.ejb and destinationLookup, it is the same model; only the prefix changed.
Common mistakes
- Throwing on permanent failures. The message loops through redelivery until the broker's limit. Route to an error queue and return normally.
- Non-idempotent handlers. Redelivery after a crash between commit and acknowledgement — rare but real — processes the message twice. Deduplicate on message id or business key.
- Bean-managed transactions in an MDB. Acknowledgement and your transaction are decoupled; you can lose or double-process messages. Use container-managed transactions.
- Selectors on queues without a catch-all consumer. Unmatched messages accumulate silently. Monitor queue depth, or use a topic.
- Assuming ordered processing. The pool processes in parallel. Design for it or constrain the pool.
ObjectMessagewith domain classes. Version coupling and deserialisation risk. Use JSON in aTextMessage.- Closing an injected
JMSContext. The container owns it; closing throws or breaks later calls. Create your own context from aConnectionFactoryonly in code that runs outside the container's management.
Key takeaways
- A message-driven bean turns a queue or topic into a method call: the container manages the connection, a pool of instances and the transaction around each
onMessage. - Activation properties (
destinationLookup,destinationType,messageSelector, subscription settings) are standard; pool size, redelivery limits and dead-letter handling are broker and server configuration. - With container-managed transactions, acknowledgement is part of the commit: a normal return acknowledges, an exception rolls back and triggers redelivery.
- Inject
JMSContextto send; it joins the surrounding JTA transaction so database writes and outgoing messages commit together. - Durable subscriptions keep topic messages while the consumer is down, shared subscriptions let a pool or cluster consume them, and selectors filter at the broker.
- Consumers must be idempotent, validate early, and divert unprocessable messages instead of throwing forever.
- Messaging 3.1 changed nothing functionally; the MDB model is the same as in Java EE 7 with
jakarta.*packages.
Sources and further reading
Frequently asked questions
- What happens to a message when onMessage throws an exception?
- With container-managed transactions (the default), the transaction is rolled back and the message is not acknowledged, so the broker redelivers it. If the cause is permanent — a malformed payload, a missing record — the same failure repeats until the broker's redelivery limit moves the message to a dead-letter queue. Validate early and route unprocessable messages to an error destination yourself rather than throwing repeatedly.
- Can a message-driven bean be called directly like a session bean?
- No. An MDB has no client view; only the container calls it, in response to a message. If you need the same logic elsewhere, put it in a session or CDI bean and have the MDB delegate to it — which also makes the logic unit-testable without a broker.
- Are messages consumed in order?
- A queue delivers in order to a single consumer, but the container runs a pool of MDB instances in parallel, so messages that arrive in order are processed concurrently and may complete out of order. If ordering matters, set the pool size to one, use message groups (a broker feature), or design the handler so that ordering does not matter.
- Does Jakarta EE include a message broker?
- The platform requires a JMS provider but does not say which. GlassFish and Payara embed OpenMQ, WildFly embeds ActiveMQ Artemis, Open Liberty has an embedded messaging engine, and every server can connect to an external broker such as ActiveMQ Artemis, IBM MQ or RabbitMQ (through a JMS client or a resource adapter).