The JTA and JTS/OTS specs are ambiguous with respect to the circumstances in which beforeCompletion synchronizations should be invoked.
"The Synchronization.beforeCompletion method is called prior to the start
of the two-phase transaction commit process. This call is executed with the
transaction context of the transaction that is being committed."
"The beforeCompletion method is called by the transaction manager prior to the start of the two-phase
transaction commit process. This call is executed with the transaction context of the transaction that is being
Interestingly the change log for the JTA spec also includes this revision:
"Interface javax.transaction.Synchronization, method
beforeCompletion, change the following phrase in the description "start of
the transaction completion process" to "start of the two-phase transaction
which could be read as implying that beforeCompletion should not be called when a transaction is being committed via a onePhase commit optimization. However, that interpretation makes little sense and is accordingly rejected - beforeCompletions will always be run before a xa resource commit in either phase.
Nevertheless, that still leaves open the question of the intended behaviour in cases such as the sequence
In general we take the view that beforeCompletions are intended to allow cached data to be flushed to stable store and thus invoking them when it is already known the transaction cannot commit, is a waste of time. However, this is considered an optimization rather than an absolute requirement.
A more extreme view appears to be taken by the EJB spec and testsuite, which expects the beforeCompletion will definitely NOT run after a setRollbackOnly, although it seems to have little basis for this assertion.
To allow for this ambiguity, the behaviour of the system should be configurable.