@Component
public class MutilThreadTransactionManagerUtil {
private static final Logger logger = LoggerFactory.getLogger(MutilThreadTransactionManagerUtil.class);
private static PlatformTransactionManager transactionManager;
@Autowired
public MutilThreadTransactionManagerUtil(PlatformTransactionManager transactionManager){
MutilThreadTransactionManagerUtil.transactionManager=transactionManager;
}
/**
* 每个子线程事务 在外部事务完成后 提交或者回滚
*
* @param tasks 实际任务接口列表
* @param executorService 线程池
* @throws Exception TODO: 当前tasks.size() 必须<=核心线程数,否则死锁
*/
// @Transactional
public static void execTasks(List<ITask> tasks, ExecutorService executorService) throws Exception {
ArrayList<Runnable> runnables = new ArrayList<>();
// 线程执行完标志
CountDownLatch taskCount = new CountDownLatch(tasks.size());
CountDownLatch mainCount = new CountDownLatch(1);
AtomicBoolean isCommit = new AtomicBoolean(true);
final Exception[] exception = new Exception[1];
for (ITask task : tasks) {
runnables.add(new Runnable() {
@Override
public void run() {
DefaultTransactionDefinition transactionDefinition = new DefaultTransactionDefinition();
transactionDefinition.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
TransactionStatus status = transactionManager.getTransaction(transactionDefinition);
try {
task.task();
// 任务正常执行完成
taskCount.countDown();
mainCount.await();
if (isCommit.get()) {
transactionManager.commit(status);
} else {
transactionManager.rollback(status);
}
} catch (Throwable ex) {
isCommit.set(false);
transactionManager.rollback(status);
exception[0] = new Exception(ex.getMessage(), ex);
taskCount.countDown();
logger.error(ex.getMessage(), ex);
}
}
});
}
try {
afterTransaction(mainCount, isCommit);
for (Runnable runnable : runnables) {
executorService.submit(runnable);
}
taskCount.await();
if (!isCommit.get()) {
// 子线程有异常
throw new BusinessException(exception[0].getMessage(), exception[0]);
}
} catch (Throwable ex) {
logger.error(ex.getMessage(), ex);
throw new BusinessException(ex.getMessage(), ex);
}
}
private static void afterTransaction(CountDownLatch mainCount, AtomicBoolean isCommit) {
TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
@Override
public void afterCompletion(int status) {
super.afterCompletion(status);
if (status != TransactionSynchronization.STATUS_COMMITTED) {
// 事务没有提交
logger.error(com.yonyou.iuap.ucf.common.i18n.MessageUtils.getMessage("P_YS_IMP_WIM-BE_1500480720826531984") /* "------事务回滚" */);
isCommit.set(false);
} else {
logger.info(com.yonyou.iuap.ucf.common.i18n.MessageUtils.getMessage("P_YS_IMP_WIM-BE_1500480720826532230") /* "------事务提交" */);
}
mainCount.countDown();
}
});
}
}
多线程下保证每个线程事务状态和主线程一致
最新推荐文章于 2024-06-12 21:51:25 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)