如何实现自旋锁以避免阻塞 [英] How to implement a spinlock to avoid blocking

查看:211
本文介绍了如何实现自旋锁以避免阻塞的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下代码:

// Below block executed by thread t1
synchronized(obj) {
   obj.wait(0);
}

// This block executed by thread t2
synchronized(obj) {
    obj.notify();
}

我理解在上面的代码中,如果t1拥有同步块的所有权,并且同时如果线程t2试图获取同步块,则t2会进行内核等待. 我想避免这种情况,并在块之前旋转t2,直到t1调用等待并离开该块的所有权为止.有可能吗?

I understand that in above code if t1 has taken ownership of synchronized block and at the same time if thread t2 tries to take synchronized block, then t2 goes for a kernel wait. I want to avoid this situation and spin t2 before the block until t1 calls wait and leaves ownership of the block. Is that possible?

推荐答案

JVM不需要将进入锁定的同步块的条目作为硬块和上下文切换来实现. 它可以选择使用重量更轻的方法,例如旋转锁一个>.实际上,Oracle JVM使用一些长度来避免阻塞.因此,您可能会发现JVM已经为您完成了此优化.如果没有,那可能是因为JVM有证据表明自旋锁将是一个坏主意.

The JVM need not implement entry to a locked synchronized block as a hard block and context switch. It has the option of using lighter weight methods, such as spin locks. In fact, the Oracle JVM goes to some lengths to avoid blocking. So you might find that the JVM has already done this optimisation for you. And if it has not, that might be because the JVM has evidence that a spin lock would be a bad idea.

这篇关于如何实现自旋锁以避免阻塞的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆