Search code examples
c#nhibernateconcurrencytransactionsoptimistic-concurrency

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.

  1. 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


Solution

  • 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.

    1. Have a Thread.Sleep() between the Get() and Update() methods, for only one user(process 1 ).

    2. When process 1 is running , start process 2 which doesnt encounter the Thread.Sleep() and completes the update before the process 1 does .

    3. 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);
        }