多线程与事务回滚

一、背景:

        使用javax.jms.MessageListener监听消息,监听到消息后使用线程执行器ThreadPoolExecutor进行业务处理,并配置了事务JmsTransactionManager,当业务处理出现异常时,进行回滚操作。

二、问题:

       业务中可能出现的两类异常:

          1.业务处理出现checked exception必须在线程中捕获处理不允许抛出;

          2.如果线程抛出unchecked exception,则线程终结,主线程不受影响。

       基于以上对线程处理异常的认识,可以确定使用多线程处理业务中出现的异常在主线程中无法捕获,即无法实现回滚。

三、解决办法:

      使用Callable接口(Executor Framework的优势之一:可以运行并发任务并返回结果)。

线程执行器业务处理代码:

ThreadPoolExecutor executor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize,
				KEEP_ALIVE_TIME, UNIT, new ArrayBlockingQueue<Runnable>(
						queueSize));
Future<String> future = executor.submit(new Callable<String>() {
			public String call() {
     try {
       ……
      } catch (Exception e) {
     //捕捉到异常时进行异常处理并返回failed
    return  “failed”;
    }
    //业务处理正常则返回success
   String result = "failed";
   	try {
               //通过回调获取线程执行是否出现异常
			result = future.get();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ExecutionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    return result;
   }
});
监听器实现事务回滚代码:

// 消息进行业务处理并返回处理结果,sucess(成功),failed(失败)
String result = serviceConfiguration.getServerProcessThreadPool().process(message);
// 获取到业务处理异常时即result为"failed",抛出运行时异常进行事务回滚
if ("failed".equals(result)) {
	throw new RuntimeException();
}

 
 
 

  • 4
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值