We have following method in our code which has Transactional annotation and is synchronized.
@Transactional(propagation=Propagation.REQUIRED, rollbackFor=Exception.class)
public synchronized void addValueToDB(String value, int parent) {
int nextId = getNextIDUsingSequence();
insertIntoDB(nextId, value);
updateLeft(parent);
updateRight(parent);
}
Now as Transactional annotation commits in database after method completion so synchronization on this method seems useless to me? Does spring provides any solution to this or should I synchronize the block from where this method is getting called?
transactions and synchronization are two different things:
a TX (transaction) means your code will not see the effects of other TXs running alongsde it (up to a point...), but wont prevent other TX from running. for example you could try and alter the same database row from 2 TXs. one (the 1st to commit) will succeed and the other would fail.
synchronization prevents multiple thread from executing your method (on the same instance of your class. is your class a singleton?) at the same time. it offers much more powerful isolation
you need to decide which of the 2 you need
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With