Java Reference
In-Depth Information
In progress: Successful event
After completion message: Successful event
After success message: Successful event
The
onInProgress
method is invoked immediately when the event is i red and while the transaction is
still in l ight. The other two methods—
onCompletion
and
onSuccess
—must wait until the transaction
reaches the
AFTER _ COMPLETION
and
AFTER _ SUCCESS
phases, respectively, before they can execute.
S
Next you'll look at the
getSixthChild
method, which fails by causing an
IndexOutOfBoundsException
. The output that results from calling this method follows:
In progress: Rollback event occurred.
Exception caught.
After completion message: Rollback event occurred.
After failure message: Rollback event occurred.
As before, the
onInProgress
method is invoked immediately, and the
onCompletion
and
onFailure
methods must wait until the method completes. Once the
onInProgress
method
outputs the message
Exception caught
and the transaction is marked for rollback by
calling the
SessionContext
method
setRollbackOnly
, the
y onInProgress
method completes, and
you can execute your observers. The
onCompletion
method is executed, followed by the
OnFailure
method.
The
setRollbackOnly
method marks the current transaction for rollback, so it can never be
committed. This action triggers the transaction into the
AFTER _ FAILURE
phase and invokes the
onFailure
method.
Observers can also be given conditional behavior, although it's limited to being notii ed if an
instance of the bean that dei nes the observer method already exists in the current context.
The observer method is called only if an instance exists. To dei ne an observer method as
conditional, add
notifyObserver = Reception.IF _ EXISTS
as an argument to the
@Observes
annotation.
import javax.enterprise.event.Reception;
public void addMember (
@Observes(
notifyObserver = Reception.IF_EXISTS
) String message){
// Implementation code.
}
The default behavior is to create an instance if it does not exist.
WHERE AND WHEN TO USE THE OBSERVER PATTERN
The observer pattern, which can unleash huge performance gains, is an effective way to promote
loose coupling and change the direction of calling/listening.
When designing your application or refactoring another's code, watch out for unnecessary and time
interval‐based method executions, which can be good candidates for implementing the observer pattern.