在多线程环境中处理事务 [英] Handling transaction in multithreaded environment

查看:1699
本文介绍了在多线程环境中处理事务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

需要使用多个线程在数据库中插入数据,但是即使单个线程提交失败,所有事务也必须回滚.尝试通过以下方法解决此问题.

在线程之间共享连接对象,并使用join()等待子线程完成,但这看起来像是糟糕的设计,因为我正在线程之间共享连接对象.

有人可以建议更好的设计来解决此问题吗(不确定我是否应该使用分布式txn管理器)?

我建议将来自多个线程的所有SQL操作以某种中间数据结构排队,然后从单个线程放入数据库中.可能具有诸如ConcurrentHashMapConcurrentLinkedQueue之类的线程安全中间结构,或者您可以在使用它们时进行同步.

这样,您甚至不需要提前开始交易.暂挂的数据可能不太安全,但是我认为当事务尚未提交时,它们在数据库中的安全性要差得多.

当然,仅当您没有select语句从同一事务中选择未提交的事务数据时,此方法才有效.摆脱这种查询的一种或另一种方式可能需要重新设计.

使用CountDownLatch来检测所有数据何时准备就绪,并且数据库写入线程应开始其操作.如果永远不会发生,请对数据库写入线程使用反应堆模式.

Need to insert data in database using multiple threads ,but even if a single thread fails to commit,all transaction must rollback.Tried to solve this by below approach.

Sharing connection object among thread,and using join() to wait for child thread to finish,but this looks like bad design,as i am sharing connection object among threads.

Can someone suggest better design to solve this (Not sure should i go for distributed txn manager or not)?

解决方案

I would suggest to queue all SQL actions from multiple threads in some intermediate data structure, and then put into database from a single thread. It is possible to have the thread safe intermediate structures like ConcurrentHashMap, ConcurrentLinkedQueue or you may just synchronize when working with it.

This way you even do not need to start the transaction in advance. The pending data may be less safe, but I assume they are not a lot safer in the database while the transaction is not committed yet.

Of course, this can only work if you do not have select statements picking uncommitted transaction data from the same transaction. Getting rid of such queries one or another way may require redesign.

Use CountDownLatch to detect when all data are ready and the database writing thread should start its action. If never happens, use reactor pattern for the database writing thread.

这篇关于在多线程环境中处理事务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆