CountDownLatch子线程事务提交与回滚

@RunWith(SpringRunner.class)
@SpringBootTest(classes = WebApplication.class)
@EnableAutoConfiguration
public class SpringBootTest {

    @Autowired
    @Qualifier("threadPoolWorkRule")
    private ThreadPoolTaskExecutor fixedThreadPool;
    @Autowired
    private PlatformTransactionManager transactionManager;
    @Autowired
    private LogMapper logMapper;


    @Test
    @Rollback(value = false)
    @Transactional
    public void TestCountDownLatch() {
        ExecutorService executorService = Executors.newFixedThreadPool(3);
        CountDownLatch cdl = new CountDownLatch(3);
        // 是否存在异常
        AtomicReference<Boolean> isError = new AtomicReference<>(false);
        genTx(cdl, isError);
        try {
            cdl.await();
            System.out.println("三个执行线程结束");
        } catch (InterruptedException e) {
            e.printStackTrace();
            System.out.println("执行线程异常");
        } finally {
            executorService.shutdown();
            System.out.println("执行线程关闭");
        }


    }
    /**
     * 异常测试
     * 
     * @param finalNum
     */
    public void function(int finalNum) {
        System.out.println("方法" + finalNum);
        int a = 10 / finalNum;
        // 记录日志
        DocumentLog documentLog = new DocumentLog ();
        documentLog.setDocumentNo("1-1-1-1-1-1");
        documentLog.setRemark(finalNum + "");
        logMapper.insert(documentLog);
    }

    public void genTx(CountDownLatch cdl, AtomicReference<Boolean> isError) {
        for (int i = 0; i < 3; i++) {
            int finalNum = i;
            fixedThreadPool.submit(() -> {
                DefaultTransactionDefinition def = new DefaultTransactionDefinition();
                def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
                TransactionStatus status = transactionManager.getTransaction(def);
                try {
                    function(finalNum);
                } catch (Exception e) {
                    isError.set(true);
                    e.printStackTrace();
                } finally {
                    cdl.countDown();
                }
                try {
                    cdl.await();
                    // 所有线程一起提交事物
                    if (isError.get()) {  // 事务回滚                   
                        transactionManager.rollback(status);
                    } else {  //事务提交          
                        transactionManager.commit(status);
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
        }
    }

}

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值