Java EE / Jakarta EE
Jakarta Transactions (JTA 2): Container-Managed Transactions, Propagation and XA
Intermediate9 min readUpdated
Jakarta Transactions (JTA) is the service that lets the container begin, commit and roll back work across a database, a message broker and any other enlisted resource. After reading this you will know what a transaction guarantees and what isolation levels leave open, how each propagation attribute behaves, which exceptions roll back and why, when to use bean-managed transactions, and what XA two-phase commit costs — plus the self-invocation and long-transaction mistakes that undermine all of it.
What you will learn
- Explain ACID properties, isolation levels and the anomalies each level allows
- Apply @Transactional and @TransactionAttribute with the right propagation type
- Predict when the container rolls back: system versus application exceptions, rollbackOn and setRollbackOnly
- Use UserTransaction for bean-managed transactions where declarative boundaries do not fit
- Decide when XA two-phase commit is necessary and what alternatives exist
A transaction is a promise the platform makes on your behalf: everything inside the boundary happens completely or not at all, and nobody else sees the half-done state. In Jakarta EE that promise is kept by the Jakarta Transactions service — still universally called JTA — which the container uses around every enterprise-bean method and every @Transactional CDI method, and which also coordinates JPA, JMS and JDBC resources so that one commit covers all of them. Developers rarely call JTA directly; they configure it with annotations, and then meet its rules the first time an exception does not roll back, a nested call does not get its own transaction, or a message is sent for an order that was never saved. This guide explains the rules well enough to predict those cases.
What a transaction guarantees
The ACID properties describe the contract:
- Atomicity — all the operations in the transaction take effect, or none do.
- Consistency — the transaction moves the database from one valid state to another; constraints hold at commit.
- Isolation — concurrent transactions do not see each other's intermediate state (to a degree that depends on the isolation level).
- Durability — once committed, the changes survive a crash.
Isolation is the negotiable one, because full isolation costs throughput. The SQL standard defines four levels by which anomalies they permit:
| Level | Dirty read | Non-repeatable read | Phantom read | Typical cost |
|---|---|---|---|---|
READ UNCOMMITTED | possible | possible | possible | lowest; rarely used |
READ COMMITTED | prevented | possible | possible | default on PostgreSQL, Oracle, SQL Server |
REPEATABLE READ | prevented | prevented | possible (prevented on some engines) | default on MySQL InnoDB |
SERIALIZABLE | prevented | prevented | prevented | highest; retries on conflict |
A dirty read sees uncommitted data from another transaction; a non-repeatable read gets a different value when re-reading the same row; a phantom sees new rows appear in a repeated range query. READ COMMITTED plus optimistic locking (@Version in JPA) is the combination most business applications run on: reads are cheap, and lost updates are caught at write time rather than prevented by locks. Note that JTA itself does not set the level — configure it on the data source.
Local versus global transactions
A local transaction involves one resource: a single JDBC connection's commit(). The database does all the work and JTA merely tells it when. A global (distributed) transaction spans several resources — two databases, or a database and a message broker — and needs a coordinator that can make them all commit or all roll back. JTA provides that coordinator, the transaction manager, and resources participate through the XA interface (javax.transaction.xa.XAResource, which stayed in the Java SE namespace).
In a server, resources are declared as XA or non-XA data sources and connection factories. Enlisting a non-XA resource in a transaction with another resource is either refused or handled with a vendor "last resource commit optimisation", which is not fully safe. Most applications use one database and are better off with a non-XA data source: simpler, faster, and the transaction manager still gives you declarative boundaries and rollback.
Container-managed transactions
The container demarcates the transaction around a method call and decides, from an annotation, how the method relates to any transaction already running in the caller. The six propagation types are the same for @TransactionAttribute on enterprise beans and @Transactional on CDI beans:
| Type | Caller has a transaction | Caller has none |
|---|---|---|
REQUIRED (default) | Join it | Start a new one, commit on return |
REQUIRES_NEW | Suspend it, run in a new one, resume after | Start a new one |
MANDATORY | Join it | Throw TransactionalException / EJBTransactionRequiredException |
SUPPORTS | Join it | Run without a transaction |
NOT_SUPPORTED | Suspend it, run without | Run without |
NEVER | Throw | Run without |
REQUIRED is right for almost every business method: the outermost call owns the transaction and inner calls join it, so a service that calls two repositories gets one atomic unit. REQUIRES_NEW is for work that must commit even if the caller fails — an audit record, a "processing failed" status — and it costs a second connection and, with XA, a second branch. MANDATORY documents that a method is never an entry point. NOT_SUPPORTED and SUPPORTS are for read-only paths that should not hold a transaction, such as long report queries; NEVER is a guard against being called inside one.
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import jakarta.transaction.Transactional;
import jakarta.transaction.Transactional.TxType;
@ApplicationScoped
public class PaymentService {
@Inject OrderRepository orders;
@Inject PaymentGateway gateway;
@Inject AuditLog audit;
@Transactional // REQUIRED: one unit for the whole method
public void pay(Long orderId, CardToken card) {
Order order = orders.find(orderId);
try {
gateway.charge(order.total(), card); // external call; cannot be rolled back
order.markPaid(); // dirty-checked, written at commit
} catch (PaymentDeclinedException e) {
audit.record(orderId, "declined: " + e.code()); // survives the rollback below
throw e; // marked rollbackOn, so the order stays unpaid
}
}
}
@ApplicationScoped
public class AuditLog {
@PersistenceContext EntityManager em;
@Transactional(TxType.REQUIRES_NEW) // its own transaction, committed independently
public void record(Long orderId, String event) {
em.persist(new AuditEntry(orderId, event));
}
}
For this to work as intended, PaymentDeclinedException must roll back the outer transaction. Which brings us to the rules.
What rolls back
Both annotations distinguish two kinds of failure. A system exception — any RuntimeException or Error — is treated as a bug or an infrastructure failure: the container marks the transaction for rollback, and for enterprise beans wraps it in EJBException and discards the instance. An application exception — a checked exception — is treated as a business outcome: the transaction commits and the exception propagates unchanged.
You can override the default for each side:
@Transactional(rollbackOn = PaymentDeclinedException.class)rolls back on that checked exception;dontRollbackOn = ValidationException.classcommits despite that runtime exception.- On enterprise beans, annotate the exception class with
@ApplicationException(rollback = true); that also stops a runtime exception from being wrapped inEJBException. - Programmatically, inject
TransactionManagerorEJBContextand callsetRollbackOnly(). The transaction continues but can no longer commit — aRollbackExceptionis thrown at the boundary — which is what a validation step deep in the call chain should do when it cannot throw.
Once a transaction is marked for rollback, nothing un-marks it. A common surprise: an inner REQUIRED method throws a runtime exception, the outer method catches it and continues, and the outer commit fails with RollbackException — because the inner failure already doomed the shared transaction.
Timeouts
Every server has a default transaction timeout (commonly 300 seconds); when it expires the transaction is rolled back from a reaper thread and the next resource access fails. Set shorter limits on long-running methods with vendor annotations (@TransactionTimeout on WildFly) or by calling UserTransaction.setTransactionTimeout in bean-managed code. A transaction that needs minutes usually indicates a batch that should be chunked.
Bean-managed transactions
When the boundaries do not line up with method calls — a batch loop that commits every thousand records, a method that must decide at runtime whether to start a transaction — take control with UserTransaction:
import jakarta.annotation.Resource;
import jakarta.ejb.Stateless;
import jakarta.ejb.TransactionManagement;
import jakarta.ejb.TransactionManagementType;
import jakarta.transaction.Status;
import jakarta.transaction.UserTransaction;
@Stateless
@TransactionManagement(TransactionManagementType.BEAN) // the container will not demarcate for this bean
public class ImportJob {
@Resource UserTransaction tx;
@PersistenceContext EntityManager em;
public void importAll(List<Row> rows) throws Exception {
int i = 0;
tx.begin();
try {
for (Row row : rows) {
em.persist(toEntity(row));
if (++i % 1000 == 0) { // commit in chunks: bounded memory, bounded lock time
tx.commit();
em.clear();
tx.begin();
}
}
tx.commit();
} catch (Exception e) {
if (tx.getStatus() == Status.STATUS_ACTIVE) tx.rollback();
throw e;
}
}
}
UserTransaction is available to any component through @Resource or the JNDI name java:comp/UserTransaction; CDI beans can also inject it. A stateless bean with bean-managed transactions must not return with a transaction still open — the container rolls it back and logs an error. The transaction-scoped EntityManager joins whatever transaction is active when it is used, so em.clear() after each commit keeps the persistence context from growing.
TransactionSynchronizationRegistry is the third API worth knowing: it lets you register a callback for beforeCompletion and afterCompletion, which is how you send a notification only once the commit has actually succeeded. CDI 4.0's transactional observers achieve the same thing declaratively: void onOrderPaid(@Observes(during = TransactionPhase.AFTER_SUCCESS) OrderPaid event).
XA and two-phase commit
When a transaction has enlisted two XA resources — say a PostgreSQL XA data source and an ActiveMQ Artemis connection factory — commit runs in two phases:
- Prepare. The transaction manager asks every resource to prepare: write everything needed to commit to durable storage and vote yes or no. A resource that votes yes must be able to commit later even after a crash.
- Commit. If all voted yes, the manager writes a decision record to its own transaction log and tells each resource to commit; otherwise it tells them all to roll back.
The log is what makes the protocol recoverable: if the server dies between the phases, on restart the manager reads the log and finishes the in-doubt branches. That is also the operational cost of XA — the log must be on reliable storage, it must survive redeployments and container restarts, and a resource that stays unreachable leaves in-doubt transactions holding locks until recovery completes or an administrator resolves them. Throughput is lower because of the extra round trips and forced disk writes.
Before choosing XA, consider the alternatives:
- One resource. Most services need one database. Put messages in a table (transactional outbox) and have a relay publish them; the local transaction covers both.
- Idempotent consumers. Send the message after commit and let consumers tolerate a duplicate or a message referring to a record that does not exist yet.
- Compensation. For long business processes spanning services, sagas replace atomicity with explicit compensating actions; the distributed-transactions guide discusses the trade-offs.
XA is the right choice when the resources are genuinely both critical, the volume is moderate and the operational maturity to monitor recovery exists — classic message-driven bean plus database processing is exactly that case, and the container makes it a one-line configuration change.
How the pieces fit together at runtime
Consider a session bean method with REQUIRED that persists an order through JPA and sends a JMS message through an injected JMSContext:
- The proxy asks the transaction manager to begin a transaction and associates it with the current thread.
- The first
EntityManageruse acquires a connection from the data source; the connection is enlisted. - The
JMSContextsend enlists the JMS session; the message is buffered, not delivered. - The method returns normally. The container calls the JPA provider's
beforeCompletionsynchronisation, which flushes the persistence context — theINSERTruns now, and constraint violations surface here asPersistenceException. - The manager commits: one-phase if only one resource is enlisted, two-phase otherwise. The message becomes visible to consumers only after commit.
- The persistence context closes; entities become detached.
Step 4 explains why exceptions from the database appear "after" your code finished, and why a @Transactional method cannot catch its own flush failures — the flush happens outside the method body. If you need to react to a constraint violation, call em.flush() explicitly inside the method and catch there.
Common mistakes
- Self-invocation. Calling
this.record(...)on aREQUIRES_NEWmethod runs it in the caller's transaction, because the proxy is bypassed. Inject the bean into itself or move the method to another bean. - Expecting checked exceptions to roll back. They commit by default. Use
rollbackOnor@ApplicationException(rollback = true). - Catching the inner exception and committing anyway. The transaction is already marked; commit throws
RollbackException. CheckgetStatus()(orgetRollbackOnly()on the enterprise-bean context) before continuing, or useREQUIRES_NEWfor the inner work. - Long transactions. Holding a transaction across a remote HTTP call or a user think time keeps locks and connections busy. Keep the boundary around the data access only.
- External side effects inside the transaction. An e-mail sent before a rollback cannot be un-sent. Send from an
AFTER_SUCCESSobserver or an outbox. - XA by default. Configuring every data source as XA costs performance and adds recovery to operate, for applications that never enlist a second resource.
@Transactionalon a private method or a non-CDI object. No proxy, no interceptor, no transaction. Public methods on managed beans only.
Key takeaways
- JTA gives the container a transaction manager that demarcates work and coordinates enlisted resources; ACID is the contract, and the isolation level is set on the data source, not by JTA.
REQUIREDfor business methods,REQUIRES_NEWfor work that must survive the caller's failure,MANDATORYandNEVERas guards,SUPPORTS/NOT_SUPPORTEDfor read-only paths.- Runtime exceptions roll back, checked exceptions commit; change that with
rollbackOn,@ApplicationExceptionorsetRollbackOnly. - Flush happens at commit, outside your method; call
em.flush()explicitly if you must handle database errors in place. - Use
UserTransactionfor chunked batches and runtime-decided boundaries; never leave a transaction open when a stateless bean returns. - XA two-phase commit is recoverable and correct but costs throughput and operations; prefer one resource plus an outbox unless both resources are critical.
- Calls through
thisbypass the proxy and every transaction attribute with it.
Sources and further reading
Frequently asked questions
- What is the difference between @Transactional and @TransactionAttribute?
- They configure the same container service. @TransactionAttribute (jakarta.ejb) applies to enterprise beans, whose methods are transactional by default. @Transactional (jakarta.transaction, since JTA 1.2) is a CDI interceptor binding that works on any managed bean, is opt-in, and adds rollbackOn and dontRollbackOn attributes. New code on CDI beans uses @Transactional; the propagation types are identical.
- Why did my transaction not roll back when I threw an exception?
- Because it was a checked exception. Both annotations roll back on RuntimeException and Error by default and commit on checked exceptions. Either declare @Transactional(rollbackOn = MyCheckedException.class), mark the exception class @ApplicationException(rollback = true) for enterprise beans, or call setRollbackOnly before returning.
- Do I need XA if I use one database and one message broker?
- If the database write and the message must be atomic, yes — that is exactly two resources, and only a two-phase commit makes both succeed or both fail. The alternatives are the transactional outbox pattern (write the message into a table in the same database transaction and publish it from there) or accepting a small window of inconsistency with idempotent consumers.
- Does JTA set the isolation level?
- No. JTA controls boundaries, propagation and coordination, not isolation. Isolation is a property of the connection, set on the data source in the server configuration or per connection through JDBC, and its default varies by database — READ COMMITTED on PostgreSQL and Oracle, REPEATABLE READ on MySQL's InnoDB.