why wait/notify/notifyAll methods are not synchronized in java ?

后端 未结 7 1530
生来不讨喜
生来不讨喜 2020-12-05 10:20

in Java whenever we need to call wait/notify/notifyAll, we need to have access to object monitor (either through synchronized method or through synchronized block). So my q

7条回答
  •  庸人自扰
    2020-12-05 10:57

    Among all the non-buggy codes I've read and written, all the them use wait/notify in a bigger synchronization block involving read/write of other conditions

    synchronized(lock)
        update condition
        lock.notify()
    
    synchronized(lock)
        while( condition not met)
            lock.wait()
    

    If wait/notify are themselves synchronized, no harm is done to all the correct codes (may a small performance penalty); it won't do any good either to all the correct codes.

    However, it would have permitted and encouraged a lot more incorrect codes.

提交回复
热议问题