Spring-Service-事务中线程异常执行事务回滚的方式

来源:互联网 发布:网络电视直播pc版 编辑:程序博客网 时间:2024/05/19 02:24

方式一: 使用Callable, 利用Callable的返回值判断是否需要进行事务回滚

    ExecutorService service = Executors.newCachedThreadPool();    Future<Integer> submit = service.submit(new Callable<Integer>() {        @Override        public Integer call() throws Exception {            System.out.println("bla bla ...");            return 5 * 3;        }    });    try {        if (submit.get() == 15) {            throw new RunTimeException("操作失败!");        }    } catch (InterruptedException e) {        e.printStackTrace();    } catch (ExecutionException e) {        e.printStackTrace();    }

方式二: 使用FutureTask

 Callable<Integer> integerCallable = new Callable<Integer>() {            @Override            public Integer call() throws Exception {                return 10;            }        };        ExecutorService executor = Executors.newCachedThreadPool();        FutureTask<Integer> futureTask = new FutureTask<>(integerCallable);        try {            Object o = executor.submit(futureTask).get();                throw new RuntimeException();        } catch (InterruptedException e) {            e.printStackTrace();        } catch (ExecutionException e) {            e.printStackTrace();        }        executor.shutdown();
原创粉丝点击