多线程场景下异常回滚

  • Post author:
  • Post category:其他


思路:

每个线程手动提交事务。

通过栅栏,等所有子线程都执行到栅栏处等待,最后一个子线程到到时候,通过redis里面存储的成功数量是否和总数量一致,是则提交所有事务,否则回滚所有事务。

@Service
public class TestService {
    @Autowired
    private DataSourceTransactionManager txManager;


    public void test() throws ExecutionException, InterruptedException {
        ExecutorService pool = Executors.newFixedThreadPool(4);

        List<TaskDataBase> list = new ArrayList<>();
        List<TaskDataBase> list2 = new ArrayList<>();

        TaskDataBase taskDataBase = new TaskDataBase();
        taskDataBase.setId("xxxx");
        taskDataBase.setTaskId("xxxx");
        taskDataBase.setYear("xxxx");
        taskDataBase.setMonth("xxxx");
        taskDataBase.setDate("xxxx");
        taskDataBase.setHour("xxxx");
        taskDataBase.setDateHour("xxxx");

        TaskDataBase taskDataBase2 = new TaskDataBase();
        taskDataBase2.setId("xx");
        taskDataBase2.setTaskId("xx");
        taskDataBase2.setYear("xx");
        taskDataBase2.setMonth("xx");
        taskDataBase2.setDate("xx");
        taskDataBase2.setHour("xx");
//        taskDataBase2.setDateHour("1");非空数据库会报错

        list.add(taskDataBase);
        list2.add(taskDataBase2);
        List<Future<Integer>> futures = new ArrayList<>();
        CyclicBarrier cyclicBarrier = new CyclicBarrier(2);
        String uuid = UUIDUtil.getUUID();
        for (int i = 0; i < 2; i++) {
            List<TaskDataBase> lst = i == 0 ? list : list2;
            futures.add(pool.submit(new InsertTaskDataCallable(uuid,2, txManager, lst, cyclicBarrier)));
        }
        boolean isAllSuccess = true;
        for (Future<Integer> future : futures) {
            if (future.get() == 0) {
                isAllSuccess = false;
            }
        }
        RedisUtil.del(uuid);
        System.out.println("最终结果:" + isAllSuccess);
        if (!isAllSuccess) throw new RuntimeException();
        pool.shutdown();
    }
}
/**
 * @Desc:
 * @Author: heling
 * @Date: 2020/7/16 13:41
 */
@Slf4j
public class InsertTaskDataCallable implements Callable<Integer> {

    private List<TaskDataBase> taskDataBases;
    private DataSourceTransactionManager txManager;
    private CyclicBarrier cyclicBarrier;
    private String globalId;
    private int bathes;

    public InsertTaskDataCallable(String globalId, int batches, DataSourceTransactionManager txManager, List<TaskDataBase> taskDataBases, CyclicBarrier cyclicBarrier) {
        this.taskDataBases = taskDataBases;
        this.txManager = txManager;
        this.cyclicBarrier = cyclicBarrier;
        this.globalId = globalId;
        this.bathes = batches;
    }

    @Override
    public Integer call() throws Exception {
        TaskDataMapper taskDataMapper = CxsSpringContextUtil.getBean(TaskDataMapper.class);
        DefaultTransactionAttribute def = new DefaultTransactionAttribute();
        def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
        TransactionStatus status = txManager.getTransaction(def);

        int i = 0;
        try {
            i = taskDataMapper.batchSave(taskDataBases);
        } catch (Exception e) {
            log.error("批量插入taskData异常", e);
            i = 0;
        }
        if (i > 0) {
            RedisUtil.incr(globalId);
        }
        cyclicBarrier.await();
        if (String.valueOf(bathes).equals(RedisUtil.getStr(globalId))) {
            txManager.commit(status);
        } else {
            txManager.rollback(status);
        }
        return i;
    }
}

上面是存在问题的
就是当批数大于线程池数量时候,会造成死锁,因为比如线程池有四个线程,批数为5,那么前四个批次会阻塞在await方法,那么最后一批就无法获取到线程,从而互相等待造成死锁
改进:



版权声明:本文为weixin_39035120原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。