Spring transaction manager and multithreading

后端 未结 3 904
情书的邮戳
情书的邮戳 2020-12-04 00:05

I am writing multithreading program in serviceImpl using Callable interface.I am using spring transaction manager.When update operation is executed in DB ,it is executed su

相关标签:
3条回答
  • 2020-12-04 00:31

    You haven's show how you are doing multi-threading, so I can only guess what you have done:

    In YourService.doSomething(), it createThreads. For each thread, it is doing DB related actions. Is that right?

    As desecribed in another answer, transaction context is stored in thread local manner. Therefore, your logic in thread has no association with any transaction. One thing you can verify this is, apart from the logics in threads, in doSomething() you also do some DB actions. You will find that db actions you performed in doSomething() is committed while actions in threads are lost.

    One of the reasonable way to solve is, normally we have a layer of application service which serves as a unit-of-work, and hence, we have transaction boundary on it (similar to your Service). Your thread should invoke the operations provided by the service. Of course, they will be all in different transaction.

    If you want them all in one transaction, another way is, instead of let individual thread do the DB action, threads now do the heavy work and post the result back to the originated thread (by a producer-consumer queue for example). The originated thread is responsible to gather the result and perform DB actions.

    Personally I would try to avoid manually passing the transaction context around different thread. This is simply ruining the whole idea of declarative transaction.

    0 讨论(0)
  • 2020-12-04 00:50

    The transactional context used by Spring is stored in a thread-local variable. So if you start a new thread, or execute code in another thread using a callable, this code won't be part of the transaction started by the Spring transactional aspect. That's why your data doesn't appear in the database.

    0 讨论(0)
  • 2020-12-04 00:52

    You might want to implement your own TransactionSynchronizationManager in Spring and inject it. Use something like InmheritableThreadLocal instead of ThreadLocal.

    0 讨论(0)
提交回复
热议问题