I have the following case, using C# and .NET 4.0.
I need to control that when I load a group of registers, other user can’t add a new one to this group until the first user has not finished to work with this data. This is because when one user adds a new register its data depend on the information of the all the registers of the same group.
One simple example (silly example, the real case is a bit more complex). I have a group that are int numbers. I want to have a field in my Data register that point to the max int of the group.
Group: (IDGRoup, Name, description...)
Data: (IDData, IDGroup, IDMaxData,...)
If I have two users that try to add a new int to the group, the process would be the following:
1.- load all the number from the group.
2.- Search for the max number
3.- set the IDMaxData with the ID of the max numer.
4.- Save the iformation.
The problem is that if two users load at the same time, and try to add a new int, if one of them will add the new max number of the group, the other user can’t set the correct ID to the max number, because he does not load the new max number. So the information is not coherent, because the this user set the IDMaxData to the old max number.
How to ensure that the data is coherent?
I am cosiderating to use a transaction.
1.- Load the register from Group which ID is the ID of the group that I want. If I use a transaction, with an isolation level serializable, in the moment that I load the register of the group, the second user is block because he can’t load the register. So if the second user can’t load the register of the group table, he will not can to add a new register.
2.- The first register can load all the int from Data table. He can be sure that there are all the registers because the second user can’t add a new register (he is waiting), so he can set the IDMaxData with the warranty that is the correct number.
3.- save and release the data.
The second user, that he was wating, no can load the register from Group table, and block to other users. Do the work and release the registers.
My doubt is if this is a good solution. The only problem that I can see is that I block the register of the Group table, so if someone want to update its information, must wait until the register is release. But this is a minor problem, because the information of this table will not be upadate.
There is other alternatives?
Thanks.
you are describing the technique of strict phase lock in which no transaction is allowed to begin untill the last trxn is committed. But we have other techniques also. Use simple phase lock.
you can also use timestamp ordering(TO) technique.
For more info take a look at this ppt -> Concurrency contol