Java/Hibernate: MultiThreading - write into database

43 views Asked by At

I am trying to parallelise the writing process in a JEE enironment, using Hibernate and DB2. In DB2 there are some triggers installed, so that's why I am going the way over parallelisation.

private ThreadPoolExecutor executor;

public void writeObjects(List<Element> elements){
List<Future<Void>> fElements = new ArrayList<>();
for (Element el : elements) {
     fElements.add(executor.submit(() -> writeElement(el)));
}
fElements.foreach(f->f.get()));
}

public void writeElement(Element el) {
    ElementBusinessEntity ent = convert2BusinessEntity(el);
    entityManager.persist(ent);
    enitityManager.flush();
}

So before, without parallelising, I wrote element by element and afterwards when Hibernate is closing the transaction, it was making a commit to the database and the elements are persisted. So the whole transaction is automar, when any insert is failed, than the whole transaction is rolled back.

But after parallelisation each Thread/Future is commiting its data itselelf with the disadvantage, that I have part partial data in database. So what I want to ensure is that when any Future is failed, that the whole transaction gets failed and rolled back as same as without parallelization and that the final commit is made after all threads are finished.

0

There are 0 answers