I just read Thread Signaling from Jacob Jenkov. But it has one fatal flaw: it uses a literal java.lang.String for coordinating between threads. Why is this wrong?
yes, indeed a "fatal" flaw... not :-) The only real problem is that you risk waking a few too many threads, that weren't supposed to
wake up. And what exactly does that equal? Yes, that's right, a Spurious Wakeup! ... That is why we wrap the wait() call in a while loop.
So, though I agree it is bad practice to use String's as monitor objects, it is by no chance "fatal". Nothing will happen except
you risk waking up a few threads that will then go back to waiting immediately.
I fixed the text now though, it will be online on monday or so.
Later texts in that trail will show more useful constructs like locks, read/write locks, reentrant locks, resource guards,
semaphores, blocking queues etc. I will be more careful in these texts with the choice of monitor object ;-)
,
Hmm... I dug a little bit more into this topic, and I believe that in some situations using an interned string as monitor object (calling wait() / notify() on it), can actually lead to missed signals. I'll update the text explaining this. So, if this is true, it is indeed a fatal flaw!
Comments
Jakob Jenkov replied ago:
yes, indeed a "fatal" flaw... not :-) The only real problem is that you risk waking a few too many threads, that weren't supposed to
wake up. And what exactly does that equal? Yes, that's right, a Spurious Wakeup! ... That is why we wrap the wait() call in a while loop.
So, though I agree it is bad practice to use String's as monitor objects, it is by no chance "fatal". Nothing will happen except
you risk waking up a few threads that will then go back to waiting immediately.
I fixed the text now though, it will be online on monday or so.
Later texts in that trail will show more useful constructs like locks, read/write locks, reentrant locks, resource guards,
semaphores, blocking queues etc. I will be more careful in these texts with the choice of monitor object ;-)
,
Jakob Jenkov replied ago:
Hmm... I dug a little bit more into this topic, and I believe that in some situations using an interned string as monitor object (calling wait() / notify() on it), can actually lead to missed signals. I'll update the text explaining this. So, if this is true, it is indeed a fatal flaw!
Voters For This Link (14)
Voters Against This Link (0)