Using JPA optimistic locking we can control via a @Version field if a database table has been updated by another transaction at the same time, allowing to have reliable data stored in database.
If a Java application has only one CRUD service in charge of an specific entity in database, we could synchronize its methods and manage the order the information is stored in database too.
So my question is, what's the difference between those scenarios? Does exist any advantage of performance or even best practices to follow?
Drawbacks of method synchronization:
- You will serialize the updates for all of the entity instances belonging to that entity class. Two concurrent threads will not be able to update two different instances.
- It does not work in cluster.
- Maintenance is more difficult. If the operations with the entity become more complex so it becomes possible to update the entity in multiple services, or you need to update instances of different such entity classes in the same transaction, you will have to synchronize them all.
- Point 3) increases the chances for deadlocks.
- You will have to ensure to execute the entire transaction holding the necessary synchronization locks, otherwise, if you release the lock before you commit the transaction, a concurrent transaction may obtain the lock and proceed with changing the same data.
- Depending on use cases, even if threads/transactions are not concurrent, without versioning you don't know whether the data has changed in the meantime (for example, you fetch data, modify something on the client based on the data, then somebody else changes that data, and then you save your modifications).