What are the ways to lock threads? The difference between synchronized and Lock

 The difference between Synchronized and Lock: Synchronized coding is simpler, the lock mechanism is maintained by the JVM, and the performance is better when competition is not fierce. Lock is more powerful and flexible, and performs better when competition is fierce.

  • The performance is different: when resource competition is fierce, lock performance will be better than synchronized; when competition is not fierce, synchronized will upgrade from biased lock --> lightweight lock --> heavyweight lock according to the lock competition situation. , and programming is simpler.
  • The lock mechanism is different: synchronized is implemented at the JVM level, and the system will monitor whether the lock is released or not. Lock is implemented in JDK code and needs to be released manually, which is implemented in the finally block. Locks can be acquired in a non-blocking manner.
  • Synchronized programming is simpler, and lock has more functions and is more flexible. The disadvantage is that the resource must be unlocked () in finally.
  • The usage is different: synchronized can be used on code blocks or methods. lock can only be written in the code, and the method cannot be modified directly.

Lock supported functions:

  • Fair lock: synchronized is an unfair lock. Lock supports fair lock and defaults to unfair lock.
  • Interruptible lock: ReentrantLock provides the lockInterruptly() function, which can interrupt the operation of competing for the lock. When grabbing the lock, it will check whether it is interrupted. The interruption will directly throw an exception and exit the lock grabbing. Synchronized only has the process of grabbing the lock and cannot intervene. It is not until the lock is grabbed that the release of the lock can be controlled by coding.
  • Fast feedback lock: ReentrantLock provides the functions of trylock() and trylock(tryTimes). It does not wait or waits for a limited time to acquire the lock, which is more flexible. Deadlock can be avoided.
  • Read-write lock: The ReentrantReadWriteLock class implements the function of a read-write lock, similar to Mysql. The lock itself maintains a counter. Read locks can be acquired concurrently, and write locks can only be acquired exclusively. And synchronized are all exclusive locks
  • Condition: ReentrantLock provides a more accurate thread scheduling tool than Synchronized. Condition, a lock can have multiple Conditions. For example, in the production and consumption business, a lock is accurately controlled by controlling the production Condition and consumption Condition.

Guess you like

Origin blog.csdn.net/ddwangbin520/article/details/131160257