About operation locks and file locks

The easiest way to solve concurrency problems is to use operation locks or file locks.

Synchronized and lock.

Synchronized are operation locks. The operations marked with synchronized cannot be performed by different threads at the same time. They can only be performed by the thread that preempts the resource, and the next thread can perform the same operation.


There are two forms of file lock, lock and try lock. The former is blocking. When the thread executes the statement, it will continue to execute only if the lock is obtained. Otherwise, the thread will stop at the lock statement until the lock is obtained. trylock is semi-blocking. If it does not acquire the lock, it will jump out, so try{}catch{} is used to catch it, and it will jump out.


Another point to note is that it is not possible to lock only the two steps of read() and write()



as shown in the figure above , because when one thread is performing the operation in the middle (read and write before), another thread reads the data, or will cause data errors

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326988432&siteId=291194637