Start and End an Asynchronous Business Transaction
This example shows code that starts a Business Transaction called 'CheckoutAsync' whenever
the method checkoutAsync()
is called. The originating segment created for
the Business Transaction ends when the method endSegment()
is called on the
Business Transaction, or when it is closed if used in a try-with-resources construct.
Encapsulating the method body in a try/finally block ensures that we end the segment even if
the method itself throws an exception or otherwise terminates without reaching the end.
//The thread where the Business Transaction starts
public String checkoutAsync(List<ItemOrders> orders) {
Transaction transaction = null;
try {
transaction = AppdynamicsAgent.startTransaction("CheckoutAsync", null, EntryTypes.POJO, true);
//mark handoff to link this segment with the end segment
transaction.markHandoff(commonPayload);
/*******************
* Method Body Here
*******************/
} finally {
if (transaction != null) {
transaction.endSegment();
}
}
}
Alternatively, the try-with-resources pattern is supported:
//The thread where the Business Transaction starts
public String checkoutAsync(List<ItemOrders> orders) {
try (Transaction transaction = AppdynamicsAgent.startTransaction("CheckoutAsync", null, EntryTypes.POJO, true)) {
//mark handoff to link this segment with the end segment
transaction.markHandoff(commonPayload);
/*******************
* Method Body Here
*******************/
}
}
This ends the segment in the thread where the Business Transaction was started when the try block closes. The Business Transaction itself needs to be ended in the method where the asynchronous Business Transaction ends:
//The thread where the Business Transaction ends
public String checkoutAsyncEnd(List<ItemOrders> orders, Transaction transaction, Object commonPayload) {
//link to the originating segment
Transaction transactionSegment = AppdynamicsAgent.startSegment(commonPayload);
/*******************
* Method Body Here
*******************/
if (transactionSegment != null) {
transactionSegment.endSegment();
}
if (transaction != null) {
transaction.end();
}
}