Hello -- When running the Calculator Thread example from the Kathy Sierra 1.4 book (see below, p. 533), it hangs with the following output when the calculator thread is started first . Output:
I believe the reason is that the calculator thread starts first and grabs its object lock first. This allows the notifyAll() call to occur *before* any of the other threads are waiting. Therefore, notifyAll() does nothing. If I modify the code to start the calculator thread *after* the Reader threads, the code appears to work correctly and generates the following output:
Um, can we call it an embedded "learning opportunity"? Just think, if it had actually been a *correct* example, it would have robbed you of the valuable chance to discover the problem and fix it, thus deepening and enhancing your learning. Not buying it? First, yes you ARE definitely right that the example is incorrect. And actually it's just a really bad example all the way around, even without the obvious error. We shouldn't have kept that example; I don't think it's a good idea to try to simplify a wait/notifyAll like that, but we never got around to rewriting it to be more robust with waiting in a loop, etc. Your fix does make it work (changing the order of the threads), but even *that* is not necessarily a 100% solution, since we might not even be guaranteed that the last thread started (calc thread) will NOT be the first one to run... There is still a possibility (although VERY remote) that the calc thread could still run first. Start order does not necessarily guarantee run order. So we'll have to revise that example completely for next time. In the meantime, thanks for pointing this out and for bothering to try it, and make the changes! Since you made it all the way through the last chapter of SCJP, does this mean you're planning to take the exam soon? Let us know! cheers and thanks and good catch! Kathy
posted 16 years ago
Kathy, Thanks very much for the learning opportunity Yes, I made it through the last chapter of the SCJP material, but I'm actually working *backwards* through your book (chapter by chapter). I had started with the Heller / Roberts book. After reading on javaranch that the thread questions are some of the more difficult exam questions, I jumped right to chapter 9 in your book. I plan to schedule my exam once I see how I'm doing on the mock exams (current results are confidential ). Thanks for your well-written study guide! Regards, Mark.