Listening To Transaction Progress With CDI

CDI Events are transactional. You can easily broadcast any object you like as a message:


@Stateless
public class TXTracker {
    
    @Inject
    Event<String> txListeners;
    
    @Resource
    SessionContext sc;
    
    public void success(){
        txListeners.fire("[Event] succcess");
    }

    public void failure(){
        txListeners.fire("[Event] rollback");
        sc.setRollbackOnly();
    }
}

A fully decoupled listener is going to receive all the events synchronously. In addition you can also specify the transaction phase in which the event is going to be delivered. Effectively the event's delivery is delayed, but the sender has still to wait until the completion of all listeners:


public class TXStatusListener {

    public void onInProgress(@Observes String msg){
        System.out.println("In progress: " + msg);
    }

    public void onSuccess(@Observes(during= TransactionPhase.AFTER_SUCCESS) String msg){
        System.out.println("After success: " + msg);
    }

    public void onFailure(@Observes(during= TransactionPhase.AFTER_FAILURE) String msg){
        System.out.println("After failure: " + msg);
    }
    
}


[See also an in-depth discussion in the "Real World Java EE Patterns--Rethinking Best Practices" book (Second Iteration, "Green Book"), page 209 in, chapter "Transaction Progress Listener"]

The project transaction-listener was checked in into https://kenai.com/projects/javaee-patterns/sources/hg/show/transaction-listener

See you at Java EE Workshops at MUC Airport!

Comments:

Hi, is it part of Java EE 7? Thanks

Posted by Marcin on July 08, 2013 at 05:32 PM CEST #

Hello Marcin, yes this is part of Java EE, this is CDI Events.

Posted by Vitaliy Kalayda on July 11, 2013 at 01:42 AM CEST #

any possibility of making this book available in pdf form?

Posted by Prashanth on August 07, 2013 at 08:37 PM CEST #

Post a Comment:
  • HTML Syntax: NOT allowed
...the last 150 posts
...the last 10 comments
License