This week's book giveaway is in the OCAJP forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide 1Z0-808 and have Jeanne Boyarsky & Scott Selikoff on-line! See this thread for details.
Hi Jofer, Please do not post your entire locking solution. Locking is worth 20% of the assignment, and so each person should work on it on their own. If another candidate could just copy your entire solution, then they have just gained a lot of marks without doing any work. This just lowers the value of the certification. I have therefore removed the unlock() method from your posted code. Most people can see where you are going from the lock() method alone, but anyone trying to copy your code would still have to work out how to implement the unlock() method themselves - it is not difficult, but they would have to have some idea of what they were doing. As for your code: this should be thread safe, as long as you only have one instance of lockMap for your application. Please note that swallowing the InterruptedException is a really bad idea - you should never just hide an exception in this way. If you have code like that in your submitted application you could easily loose marks for it. Doesn't your lock method have to throw some exceptions? Regards, Andrew
Hi,Andrew thank you, I regret to give all codes for the lock/unlock. you are right! I should be shrow the exception in the InterruptedException block, what's exception should be throw? thank you. [ December 10, 2003: Message edited by: Jofer Chan ]
author and jackaroo
Hi Jofer, If you search in this forum for InterruptedException you will find a lot of discussion on it. Possibly the best solution is to create your own subclass of RuntimeException, and wrap the InterruptedException in that. This way you do not need to declare it (which would break the method signatures). Regards, Andrew
Hi Jofer, Also it is a good idea to add check for the validity of the record. For ex: If record is < 0 or > than the highest number present in the DB. Also even if the record is present it is good to check if it is deleted or not. These checks can be added before wait(). This will help the thread to get out of this method quickly. Also it is good to check if record is deleted or not just before actually locking it. This help in the following scenario 1. Thread A has lock to delete the record 2. Thread B is waiting for the lock 3. Thread A deletes the record and unlocks it. 4. Now thread B can lock the record, but it should not as the record is now deleted. I guess this will help to reduce lot of deadlock situations too. Just a thought. Manoj