什么是最好的替代等待...通知低级同步? [英] What's the best alternative to wait...notify for low level synchronization?

查看:91
本文介绍了什么是最好的替代等待...通知低级同步?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我所知, wait() notify()已被更好的并发机制所取代。因此,您可以选择更好的替代方案,例如实施同步队列



在什么意义上他们是更好?



strong>:这(实现同步队列)是一个面试问题。一个可接受的答案不能使用BlockingQueue或其他队列实现。但是,它可能使用其他同步结构,如CountDownLatch。

解决方案

同步/ wait()/ notify()/ notifyAll()已被Lock类方法直接替换了 lock()/ unlock()/ newCondition() and Condition's await()/ signal()/ signalAll()



用于开始允许附加语义(诸如公平策略)以及诸如分布式锁定的特征。对多个条件对象的支持允许更细粒度的信令以及不间断的等待和等待直到某个时间等。



例如,链接的代码具有它尝试用于信令的单独的对象(由于在等待时相关监视器不被保持的事实,它将失败)。这可以通过使用具有多个条件的单个锁来直接替换。



在改进方面,附加功能可能是有价值的。在Java5中,显式Lock实现实际上比JVM监视器执行得更好,但是它们基本上削弱了Doug Lea的JVM代码,性能现在大致相当。


As far as I know, wait() and notify() have been replaced with better concurrency mechanisms. So, what better alternative would you choose, say for implementing a synchronized queue?

In what sense exactly are they "better"?

Edit: This ("implement a synchronous queue") is an interview question. An acceptable answer cannot use BlockingQueue or other queue implementation. It might, however, use other synchronization constructs such as CountDownLatch. I do not have an exhaustive list of allowed and forbidden classes - use your heads.

解决方案

synchronized/wait()/notify()/notifyAll() have been directly replaced by the Lock class methods lock()/unlock()/newCondition() and Condition's await()/signal()/signalAll().

There are several benefits to these, for a start allowing additional semantics such as fairness policies, as well as features such as distributed locking. The support for multiple Condition objects allows for much finer-grained signalling as well as uninterruptible waiting and waiting until some time etc.

For instance, the linked code has separate objects it attempts to use for signalling (which will fail due to the fact that the relevant monitors aren't held when waiting). This is directly replaceable by the use of a single Lock with multiple conditions.

In terms of improvements, the additional functionality may be of value. In Java5 the explicit Lock implementations actually performed better than the JVM monitors, but they basically nicked Doug Lea's code for the JVM and performance is now roughly equivalent.

这篇关于什么是最好的替代等待...通知低级同步?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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