0
    @Transactional(readOnly=true)
    public void upper(){
     for(int i=0;i<10;i++){
     executorService.submit(()->{
        lower();
    });
    }
    }

    public void lower(){

    }

I have above code in Spring. Does transactional(readOnly = true) is propagted to the threads in executor service and any DB modification in lower method are not allowed? We are using Hibernate ORM and MySql database

Pushparaj
  • 1,039
  • 1
  • 6
  • 26
  • entity manager isn't thread safe. you would need to create new one manually for every thread. – Michal Jun 13 '18 at 10:10
  • To my knowledge the answer is no. More importantly : why would you want it to be "yes" ? Wouldn't syncrhonization time on the same DB connection kill any gain ? Would it scale with multiple users as well as a Thread per connection model ? It's usually not that clear that it would. There is a use case for that, but it's not that trivial, so I'd think about it twice before using such a threading pattern. Not to mention : the hibernate session / EntityManager is not thread safe anyway. So unless you are fine with one Session per thread, avoid that. – GPI Jun 13 '18 at 10:29

1 Answers1

2

It will not - it's per Thread basis. Also the thread has to be managed by Spring for this to work.

Eugene
  • 117,005
  • 15
  • 201
  • 306
  • thread manager by spring means..?? The ExecutorService autowired into application by spring? If I declare a ExecutorService with a threadpool, transactional(readonly = true) will not be applicable? – Pushparaj Jun 13 '18 at 10:16
  • @Pushparaj this is entirely unclear for me - the next threads will not even have the `@Transactional` properties - there will be no transaction at all... you would have to manually create the transaction inside those threads. May be there is another way, but I am not aware of it – Eugene Jun 13 '18 at 10:20
  • if I mark like below, the threads will get into transaction? @Transactiona(readOn;y = true) public void lower(){ } – Pushparaj Jun 13 '18 at 10:27
  • @Transactionnal only works across instance/class boudaries. (You have to hit the AOP proxy, calling directly a method from within an instance does not do that) https://stackoverflow.com/questions/5109343/transactional-method-called-from-another-method-doesnt-obtain-a-transaction – GPI Jun 13 '18 at 10:38