This week's book giveaway is in the OCPJP forum. We're giving away four copies of OCA/OCP Java SE 7 Programmer I & II Study Guide and have Kathy Sierra & Bert Bates on-line! See this thread for details.
I chose to encapsulate some private methods that are used by both the update, create use cases. So what this means is that when a record is updated or deleted, the database is "checked" to see if the data was deleted FIRST before attempting to update the record or create it. Make sure your methods are thread safe (only what absolutely needs to be thread safe.) If this is the case then throw a RecordNotFoundException and recover your application in the catch clause. This performs an internal check and removes the need for this situation to arise. Also, if you haven't done it already take a look at JDK 1.5 concurrent packages. They have some pretty neat stuff in there like WriteLocks/ReadLocks.
First : Your system will perform the update functionality in two separate calls (Lock Then Update). This means that the client (user of the application) will first lock the record then update it.
Second : Regarding your case about that a thread might end up updating a record other than the record it wants to update, I have done the following :
For a client to lock a record, certainly he should have had read that record before.Now when this client wants to lock this record,read the value of this record again and also lock it. If the new value is different from the old value, display a warning to the user that this record has been changed, and update its value in whatever GUI widget used to display its value.
This solution will include the two cases : 1- The record you want to lock has been deleted and then recreated 2- The record you want to lock has been updated.
As Khaled already stressed out, that a GUI works with old data is a common use case. So the idea to inform the client that the database entry has been changed, is a good choice in my opinion. Furhtermore, to re-read the database entry and update the GUI with the lastest database entries is a good strategy.
Thank you all for your suggestions. Most probably i'll opt for matching the GUI info with that of the db file before carrying out a transaction, and showing the client a JDialog box that the db has changed (if it changes) and refresh it like you told me.