Each condition variable in Java (wait() notify()) is associated with a single mutex (synchronized).
I was said than (in Java), each mutex is also associated with a single condition variable, and that is a less efficient implementation than pthreads' cond variables and mutexes for instance. I cannot understand this one however. What does that mean? How is Java different than C/C++ pthreads on this one?
The inability to associate more than one condition variable with a single mutex is limiting. For example, suppose you want to implement a multi-producer, multi-consumer blocking queue (e.g., java.util.concurrent.ArrayBlockingQueue).
There has to be only one mutex: It won't work to have one mutex for producers and a different one for consumers. But using Java's synchronized mechanism, that means there can only be one condition variable too. That means, a consumer that makes the queue become "not-full" must signal the same condition that is signalled by a producer that makes the queue become "not-empty". And that means, that producers and consumers must notifyAll(), because otherwise there is no guarantee that the one thread that is awakened by a producer won't be another producer or, that the one thread awakened by a consumer won't be another consumer.
In a pthreads-based implementation, the queue can have one mutex, and one condition variable for producers to wait on, and a different condition variable for consumers to wait on.
Fortunately, the Java standard library provides an alternative way of locking: The java.util.concurrent.locks.Lock interface defines a mutex that can give out any number of associated Condition objects.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With