您的位置:首页 > 编程语言 > Java开发

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

2017-08-15 14:48 756 查看

方式一: 使用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();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息