Java中有各种各样的锁,例如公平锁、乐观锁等等,这篇文章主要介绍一下各种锁的分类。
- *公平锁/非公平锁
公平锁是指多个线程按照申请锁的顺序来获取锁。
不公平的锁定意味着多个线程不会按照它们申请锁定的顺序获取锁定,并且稍后应用的线程有可能优先于第一个应用的线程。可能会导致优先级反转或线程饥饿。
[En]
Unfair lock means that multiple threads do not acquire locks in the order in which they apply for locks, and it is possible that the thread that applies later takes precedence over the thread that applies first. It is possible to cause priority inversion or * thread hunger * .
公平和非公平锁的队列都基于锁内部维护的一个双向链表,表结点Node的值就是每一个请求当前锁的线程。公平锁则在于每次都是依次从队首取值。
ReentrantLock中可以在构造函数中指定其是公平锁还是非公平锁,非公平锁的优点在于吞吐量比公平锁大。
Synchronized是一种非公平锁,且无法变成公平锁。
- *乐观锁/悲观锁
乐观锁和悲观锁不是指特定类型的锁,而是指并发同步的角度。
[En]
Optimistic and pessimistic locks do not refer to specific types of locks, but to the perspective of concurrent synchronization.
悲观锁认为,相同数据的并发操作必须修改,即使没有修改,也会被视为修改。因此,对于相同数据的并发操作,悲观锁采取锁定的形式。悲观地说,解锁的并发操作肯定会出错。
[En]
Pessimistic lock believes that the concurrent operation of the same data must be modified, even if there is no modification, it will be considered modified. Therefore, for the concurrent operation of the same data, the pessimistic lock takes the form of locking. Pessimistically, unlocked concurrency operations are bound to go wrong.