Transactions and messaging
What you will learn
Transactions define atomic work within participating resources. Messaging decouples producers and consumers, but retries and failures require explicit delivery and idempotency policies.
- Describe JTA transaction and resource boundaries.
- Explain queue delivery and duplicate-safe consumption.
- Compare portable APIs with broker-specific configuration.
Plain Java examples: save as Main.java in a fresh directory, then run javac --release 21 Main.java and java Main. Jakarta EE examples require the pinned companion Maven project or separately configured illustrative infrastructure. Their predicted results are not execution evidence.
Stage a change before committing
public class Main { static class Store{int stock=4;boolean reserve(int n){if(n<=0||n>stock)return false;stock-=n;return true;}} public static void main(String[] args) {var store=new Store();System.out.println(store.reserve(2));System.out.println(store.reserve(5));System.out.println(store.stock); }}Expected output:
truefalse2This models a single state transition, not JTA or crash recovery.
Transactions and concurrency
Jakarta Transactions 2.0 provides @Transactional for managed bean methods. REQUIRED is the default type: join an existing transaction or create one. By default unchecked exceptions cause rollback; checked exceptions generally do not unless configured with rollbackOn; dontRollbackOn can override. A transaction does not automatically encompass remote HTTP or an unenlisted broker. CDI interception requires a managed invocation. Jakarta Concurrency provides managed executors and context propagation facilities; do not assume raw threads can use container contexts or that request transactions propagate to async work. WebSocket endpoints provide bidirectional sessions; apply authentication, message limits and cleanup. Jakarta Security integrates identity and authorization; restrict endpoints explicitly in production.
Messaging and failure boundaries
Jakarta Messaging 3.1 defines JMSContext, Queue, Topic, producers and consumers. A queue distributes work among consumers; a topic distributes publications to subscriptions according to subscription semantics. Redelivery can occur; make business processing idempotent using stable event IDs and a durable uniqueness constraint in the same transaction as the effect. The local model uses a set and does not survive a restart. Coordinated JTA requires compatible enlisted resources, otherwise an outbox stores a business change and event together in the database and a relay publishes later. This still needs duplicate handling. Broker address, credential and JNDI resource binding are vendor-specific. Full Platform includes Messaging; do not infer it from Web Profile. The example sender is not part of the WAR and has no broker configuration.
Ignore repeated event IDs
public class Main {
public static void main(String[] args) {var seen=new java.util.HashSet<String>();for(String id:java.util.List.of("e1","e1","e2"))System.out.println(seen.add(id)?"applied":"duplicate"); }}Expected output:
appliedduplicateappliedA volatile set is only a demonstration; use a durable atomic store in real processing.
Transactional persistence writer
Source-reviewed, NOT RUN. File lab-fixtures/jakarta-ee-v42/illustrative/BookWriter.java; use the companion lab README.
package example.persistence;import jakarta.enterprise.context.ApplicationScoped;import jakarta.persistence.*;import jakarta.transaction.Transactional;@ApplicationScopedpublic class BookWriter { @PersistenceContext(unitName="catalog") EntityManager em; @Transactional public void add(String id,String title){em.persist(new BookEntity(id,title));}}Predicted behavior: A managed invocation with configured JTA persistence context persists one entity, subject to commit.
No persistence configuration or transaction execution.
Messaging producer
Source-reviewed, NOT RUN. File lab-fixtures/jakarta-ee-v42/illustrative/NoticeSender.java; use the companion lab README.
package example.messaging;import jakarta.annotation.Resource;import jakarta.enterprise.context.ApplicationScoped;import jakarta.inject.Inject;import jakarta.jms.*;@ApplicationScopedpublic class NoticeSender { @Inject @JMSConnectionFactory("java:comp/env/jms/CatalogFactory") JMSContext context; @Resource(lookup="java:comp/env/jms/CatalogQueue") Queue queue; public void send(String eventId){context.createProducer().send(queue,eventId);}}Predicted behavior: With correctly configured JMS resources, a text event is sent to a queue.
Requires Messaging support and a broker; delivery is not verified.
Common mistakes
Do not assume annotation presence guarantees transaction interception, that messaging is exactly-once end to end, or that a memory-only set handles process restart.
Practice
Model an idempotent consumer: process e1, e2, e1, e3; print how many unique events are applied and duplicates ignored.
Expected output:
applied=3duplicates=1Compare with the manual review criteria.
Official reading: Transactions · Messaging · Inventory · Overview. Jakarta EE execution and independent review remain pending.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Transactions and messaging — knowledge check
Jakarta EE enterprise Java reasoning.
What is default @Transactional type?
Does an unenlisted HTTP call automatically roll back with JTA?
Which messaging destination distributes work among consumers?
What helps make redelivery safe?
What stores event and state in one database transaction?