java+ database lock articles
I recently encountered a problem in the company, which is about the processing of dirty data. When a user adds or changes a certain piece of data, he accesses a method at the same time, resulting in inserting two pieces of data or changing the value several times.
java's synchronized keyword
I used to understand the usage of the synchronized keyword, but I haven't actually used it, so in the case of our small business volume, this can meet the requirements and ensure concurrency. However, when method A is not executed, it cannot return the correct value. Therefore, when accessing other requests of method A at the same time, the correct value cannot be obtained. At this time, it is necessary to make a fuss on the database.
Database lock:
Let’s not talk about other categories, let’s talk about pessimistic locks and optimistic locks.
Pessimistic lock classification
1. Table lock, lock the entire table in a state that will always be updated.
2. Row locks. The scope of locks is at the row level. The database can determine which rows need to be locked and use row locks. If it does not know which rows will be affected, it will use table locks. For example, a user table user, has the primary key id and the user's birthday. When you use a statement like update ... where id=?, the database knows exactly which row will be affected, and it will use row locks. When you use update ... where birthday =? When such a statement does not know in advance which rows will be affected, table locks may be used.