Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Synchronized Transactional method in Spring

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?

like image 339
Sachin Gorade Avatar asked Mar 03 '26 21:03

Sachin Gorade


1 Answers

transactions and synchronization are two different things:

  1. 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.

  2. 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

like image 187
radai Avatar answered Mar 05 '26 12:03

radai



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!