IMHO, whether you call notify() or notifyAll() is dependant on the state that you just changed. If you changed the state, in a manner that can satisfy one waiting thread, then you call notify. If you change the state that can satisfy multiple waiting threads -- like releasing a group of semaphores, or shutting down the system (special case) -- then you call notifyAll().
I don't think it matters if you have one waiting thread, many waiting threads, or even zero waiting threads. You should design your application in a fashion where you actually don't care how many threads are waiting, if there are even any. This is why you should also (1) check the state prior to waiting, and (2) check again after waiting.
Originally posted by Petr Hejl:
It depends on behaviour of your lock method. What happens if you unlock record 1 and the thread that jvm will choose for wake up (through notify) will be waiting for record 2? It could cause a deadlock...
Originally posted by Petr Hejl:
It depends on behaviour of your lock method. What happens if you unlock record 1 and the thread that jvm will choose for wake up (through notify) will be waiting for record 2? It could cause a deadlock...
1. Thread 1 locks record 10
2. Thread 2 locks record 20
3. Thread 3 wants to lock record 10 => wait
4. Thread 4 wants to lock record 20 => wait
5. Thread 2 unlocks record 20 and call notify()
6. Thread 3 wokes up, but it still can't acquire lock on 10 => wait
7. Deadlock - no notify will ever occur
So a straight swith from notify() to notifyAll() would remedy this because each waiting thread would be notfied?
Do not set lab on fire. Or this tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
|