知识库--AkkaCommit and Rollback Events in Java(136)

    xiaoxiao2021-03-25  113

    延迟:执行真正的 事务 补偿:回滚 补偿

    public class Counter { private final Ref<Integer> value = new Ref<Integer>(1); public void decrement() { new Atomic<Integer>() { public Integer atomically() { deferred(new Runnable() {//延迟 public void run() { System.out.println( "Transaction completed...send email, log, etc."); } }); compensating(new Runnable() {//补偿 public void run() { System.out.println("Transaction aborted...hold the phone"); } }); if(value.get() <= 0) throw new RuntimeException("Operation not allowed"); value.swap(value.get() - 1); return value.get(); } }.execute(); } } public class UseCounter { public static void main(final String[] args) { Counter counter = new Counter(); counter.decrement(); System.out.println("Let's try again..."); try { counter.decrement(); } catch(Exception ex) { System.out.println(ex.getMessage()); } } }

    结果:

    Transaction aborted...hold the phone Transaction completed...send email, log, etc. Let's try again... Transaction aborted...hold the phone Operation not allowed

    结论: When the transaction completed on the first call to decrement(), the code block provided to the deferred() method is invoked. In the second call to decrement(), as soon as we hit the exception, the transaction was rolled back, and the code block provided to the compensating() method was called. We also see the rollback because of an unexpected retry at the top that’s due to the speculative configuration we discussed earlier in Nested Transactions in Java.

    转载请注明原文地址: https://ju.6miu.com/read-8148.html

    最新回复(0)