java - Optimistic locking and org.hibernate.StaleObjectStateException: -


i'm experimenting optimistic locking.

i have following class:

@entity public class student {      private integer id;     private string firstname;     private string lastname;     private integer version;  @version     public integer getversion() {         return version;     }  //all other getters ommited. } 

now i'm fetching 1 of students , try update properties concurrently.

thread t1 = new thread(new myrunnable(id));     thread t2 = new thread(new myrunnable(id));     t1.start();     t2.start(); 

and inside of myrunnable:

public class myrunnable implements runnable {     private integer id;     @override     public void run() {         session session = hibernateutil.getsessionfactory().opensession();                session.begintransaction();         student student = (student) session.load(student.class, id);         student.setfirstname("xxxx");         session.save(student);         session.gettransaction().commit();         system.out.println("done");      }      public myrunnable(integer id){         this.id = id;     } } 

what happening first transaction updates object , second transaction throws:

org.hibernate.staleobjectstateexception: row updated or deleted transaction (or unsaved-value mapping incorrect): [com.vanilla.entity.student#1] 

this ok.

my question is: 1) should if want second transaction nothing , not throw exception.

2) should if want second transaction override data updated first transaction.

thanks.

i give try answer questions:

  1. you use optimistic locking. want optimisticlockexception thrown on version conflict - can catch , nothing. can't switch off second (whatever means) transaction because don't know if version conflict occur (this essence of optimistic lock strategy: optimistic assumption version conflict won't occur often)

  2. if optimisticlockexception occurs, have 2 options:

    1. discard changes (and maybe refresh current state)
    2. refresh version of entity (entities) , try commit again

    the problem how or decide state actual "correct" (means latest) 1 if have concurrent updates. long consistency guaranteed, wouldn't care.


Comments

Popular posts from this blog

objective c - Change font of selected text in UITextView -

php - Accessing POST data in Facebook cavas app -

c# - Getting control value when switching a view as part of a multiview -