The snippet below shows the method signature for the lock method in the interface I received from Sun
The Denny’s DVD example in Andrew Monkhouse’s SCJD book specifies a timeout for threads waiting for a locked record to be released. Considering the comments on the lock method above, I believe that using a timeout violates the requirement. Instead, the thread should wait until the record it is interested in is unlocked.
Just as confirmation, did anyone use a timeout for logical record locking?
Secondly, did anyone use multiple notification objects to wake up waiting threads as suggested in Andrew’s book? I think I would rather have a thread wait on the Map which contains the locked records and have that Map notify the waiting threads (via notifyAll()), whenever a record is unlocked. Then each waiting thread can check to see whether the record it is interested in has been released or go back to the waiting state until the record is eventually released.
I also believe that having timeouts in the real SCJD project violates Sun's requirements, which is one of the reasons I put timeouts into the book's project. I think I may have mentioned that in the book somewhere.
Basically there are two very important issues we had to consider when writing the book:
We could not infringe on Sun's copyright
We did not want to devalue the SCJD process by providing a working solution to the real assignment
As such, we deliberately looked for areas where our project could be different enough to the real assignment that we met the 2 criteria above, but similar enough that it could be used as an instructional book for anyone attempting the assignment. The choice of having timeouts was one such choice.
As for your suggested locking mechanism - I know this concept is acceptable to the assessors, and many candidates have passed using it. My locking solution is far more complex, and only has a very slight gain: if implemented correctly, a thread will only be notified when the lock it is waiting for becomes available (your solution will have all threads notified, no matter which lock becomes available). Technically speaking, my solution is closer to the specification, however it is less maintainable by a junior programmer (which, if I recall correctly, is explicitly mentioned as being desirable).