Concurrency Violation in NHibernate( c#) example
For quite some time , I was reading about the optimistic concurrency in NHibernate. If what i understood was correct then the below sample should hold good.开发者_如何转开发
Consider two transactions T1 and T2.
- When T1 and T2 are done simultaneously , the state(DB entries) gets updated with the values of the most latest update.(T1 or T2).
Though it seems to be conceptually sound , how do i simulate this for the purpose of understanding and integration testing.?
Can someone help me with a sample c# code.?
Thanks ,
vijay
Conceptually :
- use 2 threads for performing T1 and 2; and a shared lock to synchronize access
- thread1 acquires lock and performs T1
- thread2 acquires the same lock and performs T2
- one of the transactions will fail with Optimistic Concurrency Exception
Now after a lot of googling , i have found out a fairly simple way to do that .The following are the steps to reproduce this.
Have a Thread.Sleep() between the Get() and Update() methods, for only one user(process 1 ).
When process 1 is running , start process 2 which doesnt encounter the Thread.Sleep() and completes the update before the process 1 does .
Now process 2 has modified the data in the data base, now when process 1 tries to update the data, NHibernate throws a stale object exception.
Please refer the following code snippet.
public void Update(int empid)
{
Employee person = this.dalService.GetByEntityId(empid);
person.Name = "Process 1";
// At this point , Update the Person table manually using raw sql query
// such as this 'Update Person Set Name = 'Process 2'where empid = @empid;
// When the update is performed , it is expected to throw the exception , as the in memory data
// is different from the one in database.
if (username.equals("Bob"))
{
Thread.Sleep(50000);
// If this is a website, have the above condition, so that it is simulated only for one user.
}
this.dalService.Update(person);
}
精彩评论