多线程场景下异常回滚

思路:

每个线程手动提交事务。

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

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


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

        List list = new ArrayList<>();
        List 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> futures = new ArrayList<>();
        CyclicBarrier cyclicBarrier = new CyclicBarrier(2);
        String uuid = UUIDUtil.getUUID();
        for (int i = 0; i < 2; i++) {
            List lst = i == 0 ? list : list2;
            futures.add(pool.submit(new InsertTaskDataCallable(uuid,2, txManager, lst, cyclicBarrier)));
        }
        boolean isAllSuccess = true;
        for (Future 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 {

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

    public InsertTaskDataCallable(String globalId, int batches, DataSourceTransactionManager txManager, List 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方法,那么最后一批就无法获取到线程,从而互相等待造成死锁
 
 
多线程场景下异常回滚_第1张图片
 
 
改进:
 
 
 
 
 
 
 
 
 
 
 

你可能感兴趣的:(JUC)