This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
As you know, the interface provided with the assignment specifies the following lock method (or something similar to it):My concern lies with the sentence that states, "the current thread gives up the CPU and consumes no CPU cycles until the record is unlocked." Now this subject has come up several times in this forum, and usually the general consensus is to use notifyAll() in the unlock method to wake up all waiting threads so they can check to see if the record they are waiting for is available. However, this technically does consume some CPU cycles, albeit a very small amount.
In Steve's Post, he outlines a waiting thread queue that he used to ensure that no CPU cycles were consumed until the specific record that a thread was waiting for is unlocked. He also received a perfect score in his locking. Personally, I think the concept of a waiting thread queue is an absolute must in a real world application. But I have always thought that it would be outside the scope of this assignment.
“Programming today is a race between software engineers striving to build bigger and better idiot-proof programs, and the Universe trying to produce bigger and better idiots. So far, the Universe is winning.” - Rich Cook
My aim was also to wake up threads only when the record lock they were waiting for had become available, thus wasting no CPU cycles. I didn't have a queue though as Steve describes, but I would just use notify to wake up a client waiting for the record lock. Sadly, I made a little error due to which in a special case threads would never be woken up (see The mysterious 65/80 locking score).
The general consensus in that discussion thread seemed to be that using notifyAll to wake up all or many clients was safer and therefore preferrable over a (slightly) more efficient approach.
For the assignment I think it is indeed beyond the scope; you can pass with 80/80 using a simple approach. It depends on your personal pride how complex you want to make it...
In fact, my version 1 used notifyAll and wait to implement locking. However, every time I saw "consumes no CPU cycles", I felt very very uncomfortable to implement locking by using notifyall and wait. Every time I saw other javaranchers got only 44/80, I thought I could fail by using only nofityall and wait. Finally I decided to implement locking by using thread queue and then I can ensure that when SUN uses multi threads to test my Data.java, my Data.java does not fail. Basically speaking, I think it is a decision that SUN wants us to make.
Thread queue is much safer but more complicated for a junior programmer. NotifyAll is easier but harder to controll thread behaviors.