java+ database lock articles

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.

        optimistic locking    

           1. As the name implies, it is very optimistic. Every time I operate the data, I think that no one will come back to modify it, so I don’t lock it, but when it is updated, it will judge whether the data has been modified during this period, and the user needs to implement it by himself. . Since there are pessimistic locks provided by the database that can be easily used, why use optimistic locks? When there are far more read operations than write operations, most of them are reads. At this time, an update operation lock will block all reads and reduce throughput. Finally, the lock needs to be released. The lock requires some overhead. We only need to find a way to solve the synchronization problem of a very small amount of update operations. In other words, if the gap between read and write ratios is not very large or your system is not responding in a timely manner, and the throughput is a bottleneck, then do not use optimistic locking, which increases complexity and brings additional risks.
            2. The general way to use optimistic locking is to add a version number field, or a timestamp. Simple.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324484984&siteId=291194637