Hello,
I am seeing different behavior with regard to locks with @Transactional and TransactionTemplate, although I assumed they would be the same. I have a need to issue numbers which are never duplicated. The main transaction which requires one of these numbers takes a while to complete so it calls a function which demands a new transaction, gets a pessimistic locak, issues the number then returns like this:-
A method that calls this had transaction template and looked like this:-Code:@PersistenceContext private EntityManager entityManager; @Transactional(propagation = Propagation.REQUIRES_NEW,readOnly = false) public int issueSequenceNumber(int id) { SequentialObject sequentialObject=entityManager.find(SequentialObject.class,id, LockModeType.PESSIMISTIC_FORCE_INCREMENT); int sequntialNumber=sequentialObject.getCurrentNumber(); sequntialNumber++; sequentialObject.setCurrentNumber(sequntialNumber); entityManager.persist(sequentialObject); return sequntialNumber; }
I think I should be able to replace this use of transaction template with an @Transactional annotaion, so the above looks like this:-Code:public void callsIssueSequenceNumber() { PlatformTransactionManager platformTransactionManager=CarrierAllocationServiceIntegrationTests.this.platformTransactionManager; TransactionTemplate transactionTemplate=new TransactionTemplate(platformTransactionManager); transactionTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); Integer mySequenceNumber=transactionTemplate.execute(new TransactionCallback<Object>() { @Override public Object doInTransaction(TransactionStatus status) { int res= sequenceService.issueSequenceNumber(); return res; } }); logger.debug("Got number "+mySequenceNumber); }
But this doesn't work. The system timesout when trying to aquire the lock:-Code:@Transactional public void callsIssueSequenceNumberAnnotaionVersion() { int mySequenceNumber= sequenceService.issueSequenceNumber(); logger.debug("Got number "+mySequenceNumber); }
I don't see why why a lock timeout should ever occur here, I'm just testing the system, there is only one thread. I also don't see why Transaction template would work when @Transaction doesn't. Can anyone suggest what is wrong with the @Transactional way of calling issueSequenceNumber and what I could do to fix it?Code:javax.persistence.LockTimeoutException: Lock wait timeout exceeded; try restarting transaction
Thanks for any help!


Reply With Quote