多线程场景下异常回滚

本文探讨了在多线程环境下使用CyclicBarrier进行事务同步的问题,特别是当任务批次数超过线程池大小时可能导致的死锁情况。通过实例展示了如何通过线程池和事务管理器在多个线程中提交事务,并在Redis中存储成功数量来判断是否全部成功,以此决定最终提交还是回滚所有事务。同时指出了当批数大于线程池数量时可能引发的死锁问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

思路:

每个线程手动提交事务。

通过栅栏,等所有子线程都执行到栅栏处等待,最后一个子线程到到时候,通过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方法,那么最后一批就无法获取到线程,从而互相等待造成死锁
 
 
 
 
改进:
 
 
 
 
 
 
 
 
 
 
 
### 关于 `CompletableFuture` 在多线程环境下发生异常时的处理 当使用 `CompletableFuture` 进行异步操作时,如果过程中抛出了未捕获的异常,默认情况下这些异常会被封装到最终的结果中。为了实现类似于事务回滚的功能,在遇到异常时可以采取以下几种策略来确保系统的稳定性和数据的一致性。 #### 使用 exceptionally 方法捕捉并处理异常 通过调用 `exceptionally(Function<Throwable, T> fn)` 可以为可能出现的失败情况指定一个替代返值或执行特定逻辑: ```java CompletableFuture<Void> future = CompletableFuture.runAsync(() -> { try { TimeUnit.SECONDS.sleep(3); // Simulate an error condition here. int i = 1 / 0; } catch (Exception e) { throw new RuntimeException(e); } }).exceptionally(ex -> { System.err.println("An exception occurred: " + ex.getMessage()); rollbackOperation(); return null; }); future.join(); ``` 此方法允许定义在任何阶段发生的错误后的恢复行为[^1]。 #### 利用 handle 方法自定义成功/失败路径 对于更复杂的场景,比如需要区分正常完成还是因为异常而终止的情况,则可采用 `handle(BiFunction<T, Throwable, U> fn)` 来分别对待这两种情形: ```java CompletableFuture.supplyAsync(() -> { // Some async operation that might fail... if (Math.random() > 0.5) { throw new IllegalArgumentException("Random failure"); } return "Success!"; }).handle((result, throwable) -> { if (throwable != null) { System.out.println("Handling failure..."); performRollbackLogic(); return false; } else { processResult(result); commitTransaction(); return true; } }); ``` 这种方式提供了更大的灵活性,可以根据实际需求调整响应机制。 #### 结合 thenCompose 实现链式调用中的异常传播与补偿措施 当有多个依赖关系的任务序列化执行时,可以通过组合不同的 `thenXxx()` 方法构建任务流水线,并利用 `thenCompose()` 将前一环节产生的结果作为输入传递给下一个阶段的同时保持对整个链条内所有潜在问题的有效监控: ```java public static void main(String[] args) throws InterruptedException, ExecutionException { AtomicBoolean transactionCommitted = new AtomicBoolean(false); CompletableFuture<String> stageOne = CompletableFuture.supplyAsync(() -> { // First step of the workflow which may succeed or fail. boolean success = Math.random() < 0.8; if (!success) { throw new RuntimeException("Stage one failed."); } return "First Stage Output"; }); CompletableFuture<Boolean> finalStep = stageOne.thenCompose(outputFromPrevStage -> doNextThingBasedOnPreviousOutput(outputFromPrevStage).whenComplete((finalOutcome, t) -> { if (t == null && finalOutcome.equals("All Good")) { transactionCommitted.set(true); } else { cleanupResourcesAndRollBackEverything(); } }) ); Boolean resultOfFinalAction = finalStep.get(); } ``` 上述例子展示了如何优雅地管理一个多步骤的工作流及其内部可能存在的各种不确定性因素。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值