公平锁和非公平锁的区别
- 锁的公平性是相对于获取锁的顺序而言的,
- 如果是一个公平锁,
- 那么锁的获取顺序就应该符合请求的绝对时间顺序,也就是FIFO。
- 非公平锁只要CAS设置同步状态成功,则表示当前线程获取了锁,
- 而公平锁则不一样,差异点有两个:
- FairSync.tryAcquire
-
final void lock() { acquire(1); }
- 非公平锁在获取锁的时候,会先通过CAS进行抢占,而公平锁则不会
-
- FairSync.tryAcquire
-
protected final boolean tryAcquire(int acquires) { final Thread current = Thread.currentThread(); int c = getState(); if (c == 0) { if (!hasQueuedPredecessors() && compareAndSetState(0, acquires)) { setExclusiveOwnerThread(current); return true; } } else if (current == getExclusiveOwnerThread()) { int nextc = c + acquires; if (nextc < 0) throw new Error("Maximum lock count exceeded"); setState(nextc); return true; } return false; } }
- 这个方法与nonfairTryAcquire(int acquires)比较,
- 不同的地方在于:
- 判断条件多了hasQueuedPredecessors()方法,
- 也就是加入了(同步队列中当前节点是否有前驱节点)的判断,
- 如果该方法返回true,则表示有线程比当前线程更早地请求获取锁,
- 因此需要等待前驱线程获取并释放锁之后才能继续获取锁。
-
- FairSync.tryAcquire