Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
362 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...