What is the cost associated with calling notify() on an Object on which no other Objects have called wait() in Java?
The reason I am interested in this is because I have a worker thread that has a queue of Objects.
The thread loops continuously checking if it has any Objects in the queue that it needs to work with. If it loops and there is nothing in said queue the thread calls wait on on a separate Object.
When another thread adds an Object to the queue it calls notify on the Object that the worker thread would be waiting on regardless if the working thread is actually waiting.
Before anyone says anything, it is all synchronized correctly and won’t throw any exceptions/errors.
My question is: is this setup slower then just having the worker thread just continue checking and never call wait() and what is the cost of calling notify() without any threads waiting on the Object?
Thanks for the help in advance 🙂
If you don’t block worker thread, it’ll be a busy-wait “spinloop” pattern, e.g. something like:
I’ve been reading about this model of conditional waiting today (in regards of my own problem :)) and found the following notes about when such model might show superior performance to ordinary
wait()–notify()scheme:The book is “Concurrent Programming in Java: Design Principles and Patterns” by Doug Lea.