java非公平锁知识点实例详解

网友投稿 306 2022-09-21


java非公平锁知识点实例详解

1、非公平锁不能保证锁的获取是按照请求锁的顺序进行的。这可能会导致某个或某些线程永远得不到锁。

2、CPU唤醒线程的费用可以降低,整体吞吐效率会很高。但是可能会有线程长时间甚至永远得不到锁,导致饿死。

实例

http:///**

* Sync object for non-fair locks

*/

static final class NonfairSync extends Sync {

private static final long serialVersionUID = 7316153563782823691L;

/**

* Performs lock. Try immediate barge, backing up to normal

* acquire on failure.

*/

final void lock() {

if (compareAndSetState(0, 1))

setExclusiveOwnerThread(Thread.currentThread());

else

acquire(1);

}

protected final boolean tryAcquire(int acquires) {

return nonfairTryAcquire(acquires);

}

}

/**

* Sync object for fair locks

*/

static final class FairSync extends Sync {

private static final long serialVersionUID = -300089789709http://0466540L;

final void lock() {

acquire(1);

}

/**

* Fair version of tryAcquire. Don't grant access unless

* recursive call or no waiters or is first.

*/

protected final boolean tryAcquire(int acquires) {

final Thread current = Thread.currentThread();

int c = getState();

if (c == 0) {

if (!hasQueuedPredecessors() &&

compareAndSetState(0, acquires)) {

setExclusiveOwnerThread(current);

http:// 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;

}

}

知识点扩展:

非公平锁,顾名思义,各个线程获取到锁的顺序,不一定和它们申请的先后顺序一致,有可能后来的线程,反而先获取到了锁。

在实现上,公平锁在进行lock时,首先会进行tryAcquire()操作。在tryAcquire中,会判断等待队列中是否已经有别的线程在等待了。如果队列中已经有别的线程了,则tryAcquire失败,则将自己加入队列。如果队列中没有别的线程,则进行获取锁的操作。

/**

* Fair version of tryAcquire. Don't grant access unless

* recursive call or no waiters or is first.

**/

protected final boolean tryAcquire(int acquires) {

final Thread DtZoNwzcurrent = 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;

}

非公平锁,在进行lock时,会直接尝试进行加锁,如果成功,则获取到锁,如果失败,则进行和公平锁相同的动作。


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:小白想要利用python脚本批量登录网络设备修改配置,看这篇就够了!
下一篇:8、关于中大型网络无线对比中小型的区别点(小型网络和大型网络的差别)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~