Spring-Service-事務中執行緒異常執行事務回滾的方式
阿新 • • 發佈:2019-02-17
方式一: 使用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();