This article is participating in the Java Theme Month – Java Debug Notes Event, see the event link for details

A preface

Transaction, it is a great concept, the programmer through manipulation of the transaction to ensure the consistency of the data, but also is a point often overlooked, why, because the function of the developers, often is a one-way development, just don’t consider the occurrence of abnormal, which is why a lot of people don’t like to write the exception handling, the same transaction itself is a compensation mechanism, It’s a technique that only works when something goes wrong.

Ii Background

Joy was working on a feature when she found a piece of code with a magic comment on it

/** * This method cannot add transaction, * @param trans * @param operator */ public void recharge(Transaction trans, String operator) { trans = this.tradeService.save(trans); this.tradeService.finish(trans, trans.getBankName(), trans.getTradeSerialNo(), operator); } @Transactional(rollbackFor = Throwable.class) public Transaction finish(Transaction trans, String bankName, String string, String operator) { trans.setBankName(bankName); trans.setReceiveString(string); trans.setStatus(Transaction.Status.Success.value()); trans.audit(operator); / / deductions successful time trans. SetDeductionDoneTime (new Date ()); trans = save(trans); return this.notify(trans); } public Transaction notify(Transaction trade) {logger.info(" Initiate Transaction notification :{}, TransactionId:{} Generates the event ",trade.getPaymentRef(),trade.getNotifyId()); this.bus.asyncPost(new JmsMessages.AfterTradeCallback(trade.getNotifyId())); return trade; }Copy the code

Code calls the way from top to bottom, first wrote a comment cannot add transaction, isn’t it strange, then we found a table was save for two times, after some time to see the thinking, because if the first method to add the transaction, then the entire invocation chain is in a transaction, and after throwing events is processing the data in another thread, So under the condition of synchronization, a transaction is not submitted, will lead to the back of the event thread can’t get a transaction to the inserted into the database data, in fact, this code is not when you start the synchronization yes, because the asynchronous processing, in a transaction, will be submitted to the event for reading data can be read here.