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;
}
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
SessionFactoryshould be good.