Reputation: 562
I have a list of Transaction objects.
List<Transaction> transactions;
I need to batch process these transactions by creating a pool of threads which update transactions concurrently. These threads update these transactions using the same DAO class(Spring singleton bean) to update the transaction. I'm using Hibernate as ORM
What am I to consider to make sure my code is thread safe? I'm a bit confused.
Here's the DAO class. SessionFactory
is also defined as a Spring bean which is then autowired to DAO class.
@Autowired
SessionFactory sessionFactory;
@Override
public Transaction update(Transaction transaction) {
Session session = sessionFactory.openSession();
session.beginTransaction();
session.update(transaction);
session.getTransaction().commit();
return transaction;
}
Upvotes: 0
Views: 1243
Reputation: 95
I think your problem is a bit bigger than threadsafety, you need to evoke transaction management. The session generated by the session factory is threadlocal (spring's HibernateTransactionManager and the beanFactory that creates the sessuinFactory -for ex: AnnotationSessionFactoryBean- manages all this stuff)
So Your code is Safe ;)
Upvotes: 1
Reputation: 2005
To get much better performance look at pooling the DB connections, there are open source implementations like c3p0 which works nicely with spring and hibernate. This is particularly import for batch processing.
Are you using the hibernate implementation of SessionFactory
? If that is the case then it is indeed thread safe so you should be good.
Another suggestion is to look at spring batch which might be useful for your situation.
Update: you've already said you are using Hibernate so the SessionFactory
should be good.
Upvotes: 1