Class TransactionManager
java.lang.Object
org.jpos.q2.QBeanSupport
org.jpos.transaction.TransactionManager
- All Implemented Interfaces:
Runnable, Configurable, QBean, QBeanSupportMBean, QPersist, TransactionConstants, TransactionManagerMBean, Loggeable, MetricsProvider
public class TransactionManager
extends QBeanSupport
implements Runnable, TransactionConstants, TransactionManagerMBean, Loggeable, MetricsProvider
Multi-participant transaction manager.
Reads contexts from a configured input space, walks each transaction through its prepare/commit/abort lifecycle, and persists state to a persistent space so in-flight transactions can be recovered after a restart.
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionclassBackground task that throttles the input queue when active sessions exceed the configured threshold.classBackground task that periodically pushes any contexts written to theRETRY_QUEUEback onto the input queue.static final recordSingle line of participant trace data accumulated on aLogEventduring a transaction's lifecycle. -
Field Summary
FieldsModifier and TypeFieldDescriptionstatic final IntegerState marker indicating a transaction is in the commit phase.static final StringSpace-key prefix used to persist a transaction's serialised context.static final StringGroup name used when no explicit group is configured.static final IntegerState marker indicating a transaction has reached its terminal state.protected Map<String, List<TransactionParticipant>> Configured group-name to participant-list mapping.static final StringSpace-key prefix used to persist a transaction's group execution stack.static final longHard ceiling on participants traversed per transaction (loop prevention).static final longDefault maximum time, in milliseconds, that a session waits for input.static final IntegerState marker indicating a transaction is in the prepare phase.static final StringSpace-key under which retried transactions are queued for re-execution.static final StringSpace-key prefix used to persist a transaction's lifecycle state.Fields inherited from class QBeanSupport
cfg, log, scheduledThreadPoolExecutorModifier and TypeFieldDescriptionprotected ConfigurationConfiguration applied to this bean by the container.protected LogLogger associated with this bean.protected ScheduledThreadPoolExecutorLazily-allocated scheduler shared with subclasses; seeQBeanSupport.getScheduledThreadPoolExecutor().Fields inherited from interface QBean
DESTROYED, FAILED, STARTED, STARTING, stateString, STOPPED, STOPPINGModifier and TypeFieldDescriptionstatic final intQBean has been destroyed.static final intQBean has failed.static final intQBean is running.static final intQBean is in the process of starting.static final String[]Human-readable names for each QBean state, indexed by state constant.static final intQBean is stopped.static final intQBean is in the process of stopping.Fields inherited from interface TransactionConstants
ABORTED, FAIL, NO_JOIN, PAUSE, PREPARED, READONLY, RETRYModifier and TypeFieldDescriptionstatic final intTransaction has been aborted.static final intShortcut for a read-only, non-joining abort (READONLY | NO_JOIN).static final intThis participant does not join the transactionstatic final intTransaction is paused.static final intTransaction has been prepared successfully.static final intContext has not been modified (no need to persist a snapshot)static final intTransaction should be retried. -
Constructor Summary
ConstructorsConstructorDescriptionCreates an unconfigured manager; configuration is supplied by Q2 at deploy time. -
Method Summary
Modifier and TypeMethodDescriptionprotected voidabort(int session, long id, Serializable context, List<TransactionParticipant> members, boolean recover, LogEvent evt, Profiler prof) Walksmembersin order, invoking each participant's abort phase and recording trace and timer information.protected voidabort(TransactionParticipant p, long id, Serializable context) Invokes the abort phase onp, swallowing exceptions (logged as warnings) and recording timer metrics.protected voidPushes a group name onto the persistent execution stack forid.voidRegisters a listener that observes transaction lifecycle transitions.protected voidLazily starts theTransactionManager.RetryTaskthat drains the retry queue back into the input space.protected voidAdvances the persistenttailpointer past any contiguous already-DONE transactions, purging their state from the space.protected voidcommit(int session, long id, Serializable context, List<TransactionParticipant> members, boolean recover, LogEvent evt, Profiler prof) Walksmembersin order, invoking each participant's commit phase and recording trace and timer information.protected voidcommit(TransactionParticipant p, long id, Serializable context) Invokes the commit phase onp, swallowing exceptions (logged as warnings) and recording timer metrics.protected voidDisables auto-commit on aJDBMSpace; no-op for other space types.protected voidRe-enables auto-commit on aJDBMSpace, flushing any pending writes; no-op for other space types.createParticipant(org.jdom2.Element e) Instantiates a participant from a<participant>element, configures it, registers per-participant timers, and tracks anyDestroyablefor cleanup at shutdown.protected StringReturns the default realm for this bean; subclasses may override.voiddump(PrintStream ps, String indent) Dumps a human-readable representation of this object to the print stream.protected LogEventfreeze(Serializable context, LogEvent evt, Profiler prof) This method gives the opportunity to decorate a LogEvent right before it gets logged.intReturns the number of session threads currently processing transactions.static <T extends Serializable>
TReturns the current thread's transaction context, narrowed to the caller's expected type.longgetHead()Returns the current head index of the transaction queue.static LonggetId()Returns the current thread's transaction id, when one is in progress.Returns the externally visible input space used for queueing contexts.longReturns the count of transactions that have been picked up but not yet completed.protected StringBuilds a persistent-space key by combining the manager name, a prefix, and the transaction id.intReturns the configured maximum number of concurrent session threads.Returns the metrics aggregator owned by this component.intReturns the number of in-flight transactions (tail - head).protected List<TransactionParticipant> getParticipants(long id) Returns the participant chain for a specific transaction, combining the default group with any groups pushed onto the persistent execution stack.protected List<TransactionParticipant> getParticipants(String groupName) Returns the configured participants for a named group.Returns the persistent space used to recover in-flight transactions across restarts.Returns the configured input queue name.static SerializableReturns the current thread's transaction context as a rawSerializable.protected intThis method returns the number of sessions that can be started at this point in timegetSpace()Returns the volatile space used for in-flight transaction state.longgetTail()Returns the current tail index of the transaction queue.getTPS()Returns the TPS counter that tracks transactions per second for this manager.Returns a human-readable summary of TPS statistics.floatReturns the average transactions-per-second since the last reset.longReturns the elapsed time in milliseconds covered by the current TPS window.intReturns the peak transactions-per-second observed since the last reset.Returns the wall-clock instant at whichTransactionManagerMBean.getTPSPeak()was reached.protected List<TransactionParticipant> initGroup(org.jdom2.Element e) Instantiates the participants declared inside a<group>element, skipping any that are explicitly disabled.protected voidinitParticipants(org.jdom2.Element config) Builds the default participant group plus any named<group>children from the QBean descriptor.voidCalled during the init lifecycle phase; subclasses may override.protected voidinitStatusListeners(org.jdom2.Element config) Instantiates and registers any<status-listener>children of the QBean descriptor.protected booleanHook used by subclasses to drain a session early.protected intprepare(int session, long id, Serializable context, List<TransactionParticipant> members, Iterator<TransactionParticipant> iter, boolean abort, LogEvent evt, Profiler prof, Chronometer chronometer) Drives the prepare phase acrossiter, accumulating results intomembersand aborting on retry signals or participant exceptions.protected intprepare(TransactionParticipant p, long id, Serializable context) Invokes the prepare phase onp, swallowing exceptions (logged as warnings) and recording timer metrics.protected intprepareForAbort(TransactionParticipant p, long id, Serializable context) InvokesAbortParticipant.prepareForAbort(long, Serializable)onpwhen applicable, swallowing exceptions and recording timer metrics.protected voidpurge(long id, boolean full) Removes persistent state associated with a transaction.voidpush(Serializable context) Pushes a context onto the head of the input queue (LIFO ordering).voidqueue(Serializable context) Enqueues a context at the tail of the input queue (FIFO ordering).protected voidrecover()Replays every in-flight transaction recorded in the persistent space, advancing the tail pointer as each completes.protected voidrecover(long id) Replays a single transaction by inspecting its persisted state and driving either the commit or abort path before purging its state.voidRemoves a previously registered status listener.voidresetTPS()Resets the TPS counters and start time.voidrun()voidConfigures this object with the suppliedConfiguration.protected voidAtomically replaces the persisted lifecycle state forid.protected voidsnapshot(long id, Serializable context) Snapshots the context for transactionidwithout changing its state.protected voidsnapshot(long id, Serializable context, Integer status) Snapshots the context and optionally updates the persisted state for transactionid.voidCalled during the start lifecycle phase; subclasses may override.voidCalled during the stop lifecycle phase; subclasses may override.protected booleantailDone()Returns whether the transaction attailis already DONE; whentrue, removes its persistent state.Methods inherited from class QBeanSupport
addAttr, close, createElement, destroy, destroyService, getAttrs, getAttrs, getConfiguration, getDump, getFactory, getLoader, getLoaderURLS, getLog, getLogger, getName, getPersist, getProperties, getProperty, getRealm, getScheduledThreadPoolExecutor, getServer, getState, getStateAsString, init, isModified, running, setAttr, setLogger, setModified, setName, setPersist, setProperty, setRealm, setServer, setState, start, stopModifier and TypeMethodDescriptionprotected voidAppends an<attr>child element with name/type/value toe.protected voidCloses a sequence ofCloseableresources, logging any failures as a warning.protected org.jdom2.ElementcreateElement(String name, Class mbeanClass) Builds a JDOMElementreflecting the bean's persistent attributes, driven by the JavaBean introspection ofmbeanClass.voiddestroy()destroy the serviceprotected voidCalled during the destroy lifecycle phase; subclasses may override.protected IteratorgetAttrs()Iterates over top-level<attr>children of the persisted element.protected IteratorIterates over<attr>children nested under the given parent element name.Returns the configuration applied to this bean.getDump()Returns a textual dump of this bean's state.Returns theQFactoryassociated with the hosting Q2 server.Returns the QClassLoader for this bean.URL[]Returns the URLs registered with the class loader.getLog()Returns theLogused by this bean.Returns the logger name.getName()Returns the bean name.org.jdom2.ElementReturns the persistent configuration element for this QBean.protected IteratorgetProperties(String parent) Iterates over<property>children nested under the given parent element name.protected StringgetProperty(Iterator props, String name) Returns the value of the named property from an iterator of<property>elements.getRealm()Returns the logging realm.protected ScheduledThreadPoolExecutorLazily creates and returns aScheduledThreadPoolExecutorfor use by subclasses.Returns the Q2 server instance.intgetState()Returns the current state of this QBean.Returns the current state as a human-readable string.voidinit()init the servicebooleanReturnstrueif this QBean's configuration has been modified since last save.booleanrunning()Indicates whether this bean is currently starting or running.protected voidUpdates the value of the named attribute within an iterator of<attr>elements.voidSets the logger by name.voidsetModified(boolean modified) Marks this bean's persistent state as modified or in sync.voidSets the bean name.voidsetPersist(org.jdom2.Element persist) Sets the persistent configuration element.protected voidsetProperty(Iterator props, String name, String value) Updates the value attribute of the named property within an iterator of<property>elements.voidSets the logging realm.voidSets the Q2 server instance for this QBean.voidsetState(int state) Sets the lifecycle state of this bean.voidstart()start the servicevoidstop()stop the serviceMethods inherited from class Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, waitMethods inherited from interface Loggeable
dumpModifier and TypeMethodDescriptiondefault voiddump(PrintStream p, String indent, LogRenderer.Type type) Dumps a representation of this object using the specified renderer type.
-
Field Details
-
CONTEXT
-
STATE
-
GROUPS
-
RETRY_QUEUE
Space-key under which retried transactions are queued for re-execution.- See Also:
-
PREPARING
-
COMMITTING
State marker indicating a transaction is in the commit phase. -
DONE
-
DEFAULT_GROUP
Group name used when no explicit group is configured.- See Also:
-
MAX_PARTICIPANTS
Hard ceiling on participants traversed per transaction (loop prevention).- See Also:
-
MAX_WAIT
Default maximum time, in milliseconds, that a session waits for input.- See Also:
-
groups
Configured group-name to participant-list mapping.
-
-
Constructor Details
-
TransactionManager
public TransactionManager()Creates an unconfigured manager; configuration is supplied by Q2 at deploy time.
-
-
Method Details
-
defaultRealm
Description copied from class:QBeanSupportReturns the default realm for this bean; subclasses may override.- Overrides:
defaultRealmin classQBeanSupport- Returns:
- default realm string, or null
-
initService
Description copied from class:QBeanSupportCalled during the init lifecycle phase; subclasses may override.- Overrides:
initServicein classQBeanSupport- Throws:
ConfigurationException
-
startService
Description copied from class:QBeanSupportCalled during the start lifecycle phase; subclasses may override.- Overrides:
startServicein classQBeanSupport- Throws:
Exception- on error
-
stopService
Description copied from class:QBeanSupportCalled during the stop lifecycle phase; subclasses may override.- Overrides:
stopServicein classQBeanSupport
-
queue
Enqueues a context at the tail of the input queue (FIFO ordering).- Parameters:
context- serialisable transaction context
-
push
Pushes a context onto the head of the input queue (LIFO ordering).- Parameters:
context- serialisable transaction context
-
getQueueName
Returns the configured input queue name.- Returns:
- the name of the input queue this manager consumes from
-
getSpace
-
getInputSpace
Returns the externally visible input space used for queueing contexts.- Returns:
- the input
Space
-
getPersistentSpace
Returns the persistent space used to recover in-flight transactions across restarts.- Returns:
- the persistent
Space
-
run
-
getTail
Description copied from interface:TransactionManagerMBeanReturns the current tail index of the transaction queue.- Specified by:
getTailin interfaceTransactionManagerMBean- Returns:
- queue tail index
-
getHead
Description copied from interface:TransactionManagerMBeanReturns the current head index of the transaction queue.- Specified by:
getHeadin interfaceTransactionManagerMBean- Returns:
- queue head index
-
getInTransit
Returns the count of transactions that have been picked up but not yet completed.- Returns:
- number of in-flight transactions
-
setConfiguration
Description copied from interface:ConfigurableConfigures this object with the suppliedConfiguration.- Specified by:
setConfigurationin interfaceConfigurable- Overrides:
setConfigurationin classQBeanSupport- Parameters:
cfg- Configuration object- Throws:
ConfigurationException- if the configuration is invalid
-
addListener
Registers a listener that observes transaction lifecycle transitions.- Parameters:
l- listener to add
-
removeListener
Removes a previously registered status listener.- Parameters:
l- listener to remove
-
getTPS
-
getTPSAsString
Description copied from interface:TransactionManagerMBeanReturns a human-readable summary of TPS statistics.- Specified by:
getTPSAsStringin interfaceTransactionManagerMBean- Returns:
- TPS snapshot suitable for diagnostics
-
getTPSAvg
Description copied from interface:TransactionManagerMBeanReturns the average transactions-per-second since the last reset.- Specified by:
getTPSAvgin interfaceTransactionManagerMBean- Returns:
- mean TPS
-
getTPSPeak
Description copied from interface:TransactionManagerMBeanReturns the peak transactions-per-second observed since the last reset.- Specified by:
getTPSPeakin interfaceTransactionManagerMBean- Returns:
- peak TPS
-
getTPSPeakWhen
Description copied from interface:TransactionManagerMBeanReturns the wall-clock instant at whichTransactionManagerMBean.getTPSPeak()was reached.- Specified by:
getTPSPeakWhenin interfaceTransactionManagerMBean- Returns:
- timestamp of the TPS peak, or
nullif not yet observed
-
getTPSElapsed
Description copied from interface:TransactionManagerMBeanReturns the elapsed time in milliseconds covered by the current TPS window.- Specified by:
getTPSElapsedin interfaceTransactionManagerMBean- Returns:
- elapsed window in milliseconds
-
resetTPS
Description copied from interface:TransactionManagerMBeanResets the TPS counters and start time.- Specified by:
resetTPSin interfaceTransactionManagerMBean
-
getMetrics
Description copied from interface:MetricsProviderReturns the metrics aggregator owned by this component.- Specified by:
getMetricsin interfaceMetricsProvider- Returns:
- the live
Metricsinstance
-
dump
-
commit
protected void commit(int session, long id, Serializable context, List<TransactionParticipant> members, boolean recover, LogEvent evt, Profiler prof) Walksmembersin order, invoking each participant's commit phase and recording trace and timer information.- Parameters:
session- session index that owns this transactionid- transaction identifiercontext- serialised transaction contextmembers- participants whose commit hooks will runrecover- whentrue, the manager is replaying a transaction after restart and should callContextRecoveryevt- optional log event to receive trace messages, ornullprof- optional profiler to receive checkpoints, ornull
-
abort
protected void abort(int session, long id, Serializable context, List<TransactionParticipant> members, boolean recover, LogEvent evt, Profiler prof) Walksmembersin order, invoking each participant's abort phase and recording trace and timer information.- Parameters:
session- session index that owns this transactionid- transaction identifiercontext- serialised transaction contextmembers- participants whose abort hooks will runrecover- whentrue, the manager is replaying a transaction after restart and should callContextRecoveryevt- optional log event to receive trace messages, ornullprof- optional profiler to receive checkpoints, ornull
-
prepareForAbort
InvokesAbortParticipant.prepareForAbort(long, Serializable)onpwhen applicable, swallowing exceptions and recording timer metrics.- Parameters:
p- participantid- transaction identifiercontext- serialised transaction context- Returns:
- result code from the participant, or
ABORTED | NO_JOINwhenpis not anAbortParticipantor threw
-
prepare
Invokes the prepare phase onp, swallowing exceptions (logged as warnings) and recording timer metrics.- Parameters:
p- participantid- transaction identifiercontext- serialised transaction context- Returns:
- result code from the participant, or
ABORTEDwhenpthrew
-
commit
Invokes the commit phase onp, swallowing exceptions (logged as warnings) and recording timer metrics.- Parameters:
p- participantid- transaction identifiercontext- serialised transaction context
-
abort
Invokes the abort phase onp, swallowing exceptions (logged as warnings) and recording timer metrics.- Parameters:
p- participantid- transaction identifiercontext- serialised transaction context
-
prepare
protected int prepare(int session, long id, Serializable context, List<TransactionParticipant> members, Iterator<TransactionParticipant> iter, boolean abort, LogEvent evt, Profiler prof, Chronometer chronometer) Drives the prepare phase acrossiter, accumulating results intomembersand aborting on retry signals or participant exceptions.- Parameters:
session- session index that owns this transactionid- transaction identifiercontext- serialised transaction contextmembers- accumulator of participants whose prepare raniter- participant iterator (may include selectors / groups)abort- whentrue, drive the prepare-for-abort pathevt- optional log event to receive trace messages, ornullprof- optional profiler to receive checkpoints, ornullchronometer- chronometer used to enforcemax-time- Returns:
- the bitwise OR of every participant result, suitable for the lifecycle dispatcher
-
getParticipants
Returns the configured participants for a named group.- Parameters:
groupName- group name (useDEFAULT_GROUPfor the default chain)- Returns:
- participants in declaration order; an empty list when
groupNameis unknown
-
getParticipants
Returns the participant chain for a specific transaction, combining the default group with any groups pushed onto the persistent execution stack.- Parameters:
id- transaction identifier- Returns:
- participants to invoke in order
-
initStatusListeners
Instantiates and registers any<status-listener>children of the QBean descriptor.- Parameters:
config- descriptor element- Throws:
ConfigurationException- if a listener cannot be instantiated or configured
-
initParticipants
Builds the default participant group plus any named<group>children from the QBean descriptor.- Parameters:
config- descriptor element- Throws:
ConfigurationException- if a group is missing a name, duplicates an existing group, or a participant fails to instantiate
-
initGroup
Instantiates the participants declared inside a<group>element, skipping any that are explicitly disabled.- Parameters:
e- group element- Returns:
- participants in declaration order
- Throws:
ConfigurationException- if a participant fails to instantiate
-
createParticipant
Instantiates a participant from a<participant>element, configures it, registers per-participant timers, and tracks anyDestroyablefor cleanup at shutdown.- Parameters:
e- participant element- Returns:
- the configured participant
- Throws:
ConfigurationException- if instantiation, configuration, or timer registration fails
-
getOutstandingTransactions
Description copied from interface:TransactionManagerMBeanReturns the number of in-flight transactions (tail - head).- Specified by:
getOutstandingTransactionsin interfaceTransactionManagerMBean- Returns:
- outstanding transaction count
-
getKey
-
commitOff
-
commitOn
-
checkTail
Advances the persistenttailpointer past any contiguous already-DONE transactions, purging their state from the space. -
tailDone
Returns whether the transaction attailis already DONE; whentrue, removes its persistent state.- Returns:
truewhen the tail transaction has reached terminal state
-
snapshot
Snapshots the context for transactionidwithout changing its state.- Parameters:
id- transaction identifiercontext- serialised transaction context, ornullto clear it
-
snapshot
Snapshots the context and optionally updates the persisted state for transactionid. Skipped when recovery is disabled and the status is notDONE.- Parameters:
id- transaction identifiercontext- serialised transaction context, ornullto clear itstatus- new persisted state, ornullto leave it unchanged
-
setState
-
addGroup
-
purge
Removes persistent state associated with a transaction.- Parameters:
id- transaction identifierfull- whentrue, also removes the lifecycle state entry (otherwise only context and group entries are cleared)
-
recover
Replays every in-flight transaction recorded in the persistent space, advancing the tail pointer as each completes. No-op when recovery is disabled. -
recover
Replays a single transaction by inspecting its persisted state and driving either the commit or abort path before purging its state.- Parameters:
id- transaction identifier
-
checkRetryTask
Lazily starts theTransactionManager.RetryTaskthat drains the retry queue back into the input space. -
freeze
This method gives the opportunity to decorate a LogEvent right before it gets logged. When overriding it, unless you know what you're doing, you should return a FrozenLogEvent in order to prevent concurrency issues.- Parameters:
context- current Contextevt- current LogEventprof- profiler (may be null)- Returns:
- FrozenLogEvent
-
getSessionsToStandUp
This method returns the number of sessions that can be started at this point in time- Returns:
- number of sessions
-
isSessionToStandDown
Hook used by subclasses to drain a session early. The default implementation never asks a session to stand down.- Returns:
trueif the current session should stop accepting new transactions
-
getActiveSessions
Description copied from interface:TransactionManagerMBeanReturns the number of session threads currently processing transactions.- Specified by:
getActiveSessionsin interfaceTransactionManagerMBean- Returns:
- live session count
-
getMaxSessions
Description copied from interface:TransactionManagerMBeanReturns the configured maximum number of concurrent session threads.- Specified by:
getMaxSessionsin interfaceTransactionManagerMBean- Returns:
- the maximum number of sessions this manager may scale up to
-
getSerializable
Returns the current thread's transaction context as a rawSerializable.- Returns:
- the thread-local context, or
nullwhen no transaction is in progress
-
getContext
Returns the current thread's transaction context, narrowed to the caller's expected type.- Type Parameters:
T- caller-supplied context type- Returns:
- the thread-local context, or
nullwhen no transaction is in progress
-
getId
-