我知道多個原因可以觸發OptimistickLockException
,但是當前的測試用例要求兩個事務同時寫入相同的數據以觸發異常。更喜歡通過並行事務創建讀/寫違規問題。這是我做過什麼:如何通過並行事務生成OptimistickLockException?
在測試類,創建一個私有字段來保存交易和一些事務性的方法:
private List<Transaction> transactions = new ArrayList<Transaction>(); // This method only generate transactions and assign // them to the member field @Transactional public void retrieveTransactions(){ transactions = generateTransactions(); // generateTransactions() is transactional } // Following two methods just write those // transactions into same summery, only the first one sleeps // during the process to make sure the second transaction // can occur in a parallel way @Transactional public void processTransactionsOne(){ for(Transaction transaction:transactions){ logger.info("====Transaction One====="); transaction.writeToSameSummary(); // writeToSameSummary() is transactional try {Thread.sleep(10000); } // sleep for 10 seconds before commit catch(InterruptedException ex) {} } } @Transactional public void processTransactionsTwo(){ for(Transaction transaction:transactions){ logger.info("====Transaction Two====="); transaction.writeToSameSummary(); // writeToSameSummary() is transactional } }
- 在
applicationContext.xml
,我在上面三種方法作爲調度製成,
retrieveTransactions
運行每60秒,processTransactionsOne
和processTransactionsTwo
運行每隔10秒<task:scheduled ref="testBeanName" method="retrieveTransactions" cron="*/60 * * * * *"/> <task:scheduled ref="testBeanName" method="processTransactionsOne" cron="*/10 * * * * *"/> <task:scheduled ref="testBeanName" method="processTransactionsTwo" cron="*/10 * * * * *"/>
但是,我永遠無法重現OptimistickLockException
和日誌顯示
====Transaction One=====
====Transaction One=====
====Transaction One=====
......
====Transaction Two=====
====Transaction Two=====
====Transaction Two=====
所以該交易正在運行,如並行同步,再也沒有起來。所以我怎麼能(1)製作parallel transactions
和(2)再現OptimistickLockException