Spring @Transactional usage with parallelStreams

Viewed 618

I have @Transactional method with big logic inside it. In different parts of it there are parallel streams that update entity objects in repositories which are changed before parallel stream.

As example:

    @Transactional
    public void someTransactionalMethod(int number) {
        SomeClass foo = someRepository.getById(number);
        foo.setState("PROCESSED");  
        //............................................................
        //..................some logic................................
        //............................................................

            getData().entrySet().parallelStream().forEach(entry -> {
                  // some heavy operation
                  someRepository.save(foo);
                  // some logic
            }
   }

The operation of saving attached object in parallel stream brings a big varity of Hibernate runtime exception as The session is closed etc. The problem is that transactions is thread local in Spring Data Jpa. But I have not find the solution how we can save entity objects from the other thread. Because in my case using one thread is very slowly to do the heavy operations that can be done fast in parallel. And at the other hand I can't delete save methods from parallel stream because the logic will be broken. What is the solution, how can we combine parallelStreams and save attached objects in transaction?

0 Answers
Related