Kiru
Kiru

Reputation: 169

How to bind a transaction to multiple threads in Hibernate?

Initially the code was in the following structure and it worked perfectly fine -

Initial code:

@Transactional
class foo
{
  void public work()
  {
      task1;
      task2;     
  }
}

As the two tasks could be executed in parallel, we refactored to put them under two threads. Wrote the two tasks in different threads, invoked them in parallel and getting the following error while the corresponding DAO is invoked

No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here

As the hibernate session is bound to the current thread, it becomes a problem with child threads.

Refactored code:

@Transactional
class foo
{
  void public work()
  {
      final Thread t1 = new Thread(new Job1());
      t1.start();

      final Thread t2 = new Thread(new Job2());
      t2.start();

      t1.join();
      t2.join(); 
  }

  class Job1
  {
     public void run()
     {
        task1;
     }   
  }

 class Job2
  {
     public void run()
     {
        task1;
     }   
  }

}

Upvotes: 2

Views: 2878

Answers (1)

axtavt
axtavt

Reputation: 242706

Even if it's possible to share Spring-managed transaction among several threads, it's not a good idea, since Hibernate transactions are bound to Sessions, and Hibernate Session is not thread-safe, so you can't use the same Session from several threads.

Perhaps it would be better to design your code in such a way that all database accesses are performed by a single thread, and other threads perform only data processing.

Upvotes: 5

Related Questions