Single transaction across multiple threads solution

前端 未结 2 1008
鱼传尺愫
鱼传尺愫 2021-02-05 12:21

As I understand it, all transactions are Thread-bound (i.e. with the context stored in ThreadLocal). For example if:

  1. I start a transaction in a transactional pare
2条回答
  •  不要未来只要你来
    2021-02-05 12:42

    First, a clarification: if you want to speed up several inserts of the same kind, as your example suggests, you will probably get the best performance by issuing the inserts in the same thread and using some type of batch inserting. Depending on your DBMS there are several techniques available, look at:

    • Efficient way to do batch INSERTS with JDBC
    • What's the fastest way to do a bulk insert into Postgres?

    As for your actual question, I would personally try to pipe all the work to a worker thread. It is the simplest option as you don't need to mess with either ThreadLocals or transaction enlistment/delistment. Furthermore, once you have your units of work in the same thread, if you are smart you might be able to apply the batching techniques above for better performance.

    Lastly, piping work to worker threads does not mean that you must have a single worker thread, you could have a pool of workers and achieve some parallelism if it is really beneficial to your application. Think in terms of producers/consumers.

提交回复
热议问题