Need help with Hibernate? Read this first:
http://www.hibernate.org/ForumMailingli ... AskForHelp
Hibernate version:H3.0.5 MSSQL 2000
Gavid had indicated in a different post that pessimistic locking works with MSSQL server in Hibernate 3. I tried it....
Here is simple java program that tries to update the same object at the same time in 2 different threads:
Code:
package my.sandbox;
import org.hibernate.LockMode;
import org.hibernate.Session;
import org.hibernate.Transaction;
public class PessimisticSpike implements Runnable {
public static void main(String[] args) throws Exception {
ThreadGroup threadGroup = new ThreadGroup("PessimisticSpike");
Thread thread = new Thread(threadGroup, new PessimisticSpike());
thread.setName("Thread " + 1);
thread.start();
Thread.currentThread().sleep(2000);//start second thread after 2 sec
Thread thread2 = new Thread(threadGroup, new PessimisticSpike());
thread2.setName("Thread " + 2);
thread2.start();
}
public void run() {
try {
String name = Thread.currentThread().getName();
System.out.println("In " + name);
Session s = HibernateAbstractSessionUtil.getCurrentSession();
Transaction tx = s.beginTransaction();
System.out.println("Reading Entity in Thread:" + name);
MyEntity e = (MyEntity ) s.load(MyEntity .class, new Long(6),LockMode.UPGRADE);
//s.lock(e, LockMode.UPGRADE);
e.setPrimaryOfficerName("J"+name);
System.out.println("Sleeping " + name);
Thread.currentThread().sleep(4000);
System.out.println("Done Sleeping " + name);
s.flush();
tx.commit();
s.close();
System.out.println("Done" + name);
} catch (Exception e) {
e.printStackTrace();
}
}
}
When i run this against oracle it works fine as expected with the following output:
In Thread 1
Reading Entity in Thread 1
Sleeping Thread 1
In Thread 2
Reading Entity in Thread 2
Done Sleeping Thread 1
DoneThread 1
Sleeping Thread 2
Done Sleeping Thread 2
DoneThread 2
Thread 2 reads only after Thread 1 id done.
But when i run the same code against MSSQL server, I got stale object exception:
In Thread 1
Reading Entity in Thread 1
Sleeping Thread 1
In Thread 2
Reading Entity in Thread 2
Sleeping Thread 2
Done Sleeping Thread 1
DoneThread 1
Done Sleeping Thread 2
org.hibernate.StaleObjectStateException:
I even tried loading the entity and then locking it using session.lock(). That didn't work either.
What am i missing?