Two methods for concurrency control of database operations in java

This article is shared from the Huawei Cloud Community " Concurrency Control of Database Operations in Java " by Zhang Jian.

In modern application coding, it is found from the database, performs some business logic operations, and finally saves it back. Right now:

Person person = personRepo.findById(id);
person.setAge(18);
personRepo.save(person);

However, in such a business operation, if one thread modifies the age, another thread modifies the nickname, and finally saves it back, it may cause the modification of one of the age/nickname to be overwritten.

There are two common solutions

Add pessimistic lock before execution

Through distributed locks and other methods, it is guaranteed that only one thread can modify the data at the same time.

Optimistic locking idea implementation

Version control is another popular way to deal with concurrency issues. It ensures data consistency by incrementing the version number every time a record is updated.

In JPA, this can @Versionbe achieved by adding annotations to the field, but this also requires that ① there must be a version field in the database, and ② for update operations after search, JPA's save method must be used to update.

Of course, you can also update_timesimulate optimistic locking implementation, which may require you to add conditions when updating update_time, and, update_timein extreme scenarios, the theoretical correctness is not so rigorous.

Click to follow and learn about Huawei Cloud’s new technologies as soon as possible~

 

Broadcom announces the termination of the existing VMware partner program deepin-IDE version update, replacing the old look with a new look Zhou Hongyi: Hongmeng native will definitely succeed WAVE SUMMIT welcomes its tenth session, Wen Xinyiyan will have the latest disclosure! Yakult Company confirms that 95 G data was leaked The most popular license among programming languages ​​in 2023 "2023 China Open Source Developer Report" officially released Julia 1.10 officially released Fedora 40 plans to unify /usr/bin and /usr/sbin Rust 1.75.0 release
{{o.name}}
{{m.name}}

おすすめ

転載: my.oschina.net/u/4526289/blog/10443380