Search code examples
javatransactionscdi

Scope of CDI events fired during a transaction


From Weld documentation:

Transactional observers receive their event notifications during the before or after completion phase of the transaction in which the event was raised.

Does this imply that the scope of CDI events fired during a transaction is limited to that transaction?

I suppose yes, but I just want to be sure that I don't have to do any cleanup when a transaction completed.


Solution

  • I think you slightly misunderstood the concept.

    There is no such thing as "scope of events". The story with transactions is as follows - you have a transactional method and within that method, you fire an event. Somewhere in your app you have observers which have the type needed to observe this event and they are also bound to certain transaction phase.

    This, in practice, means, that such observer will be notified when the transaction reaches the given state - no sooner and no later:

        public void observeAfterCompletion(@Observes(during = AFTER_COMPLETION) Foo someEvent) {
            // this will be notified once the transaction reached AFTER_CEMPLETION stage
        }
    
        public void observeBeforeCompletion(@Observes(during = BEFORE_COMPLETION) Foo event) {
            // this will be notified once the transaction reaches BEFORE_COMPLETION stage
        }
    

    For more info on when does the transaction reaches given state, you need to check with JTA spec, not CDI.

    I don't have to do any cleanup when a transaction completed.

    No you don't. You don't clean anything after standard event, no need to do it here either.