How to do notifications after a JTA commit
I had trouble finding the solution to this by googling my requirements, for some reason. I actually had to RTFM to figure it out :-(
The problem:
You have a @Stateless EJB that uses container-managed transactions to do stuff. When a transaction has committed you want to notify other parties to inform them that updates have been made. I used to make use of JMS for this, but that is truly overkill and JMS and I are no longer friends anyway. JMS is like the Post Office, you don't want to rely on them for important things like notifications.
Here is how it's done:
Note: when I implement "notifyAllMyFriends" as an @Asynchronous call, the above provides all the features that I previously used JMS for, with all the unnecessary extra fat removed!
The problem:
You have a @Stateless EJB that uses container-managed transactions to do stuff. When a transaction has committed you want to notify other parties to inform them that updates have been made. I used to make use of JMS for this, but that is truly overkill and JMS and I are no longer friends anyway. JMS is like the Post Office, you don't want to rely on them for important things like notifications.
Here is how it's done:
import javax.transaction.*;According to the specs this feature is meant to be used by the application server, but since it's so useful I can't see why anyone would ever be so heartless as to deprive poor ordinary proletarian applications of this. Anyway it works in Apache TomEE and I hope it will keep on working...
...
@Resource
TransactionManager tm;
public void doMyUpdate() {
reallyDoMyUpdate();
try {
tm.getTransaction().registerSynchronization(new Synchronization() {
public void beforeCompletion() {}
public void afterCompletion(int status) {
if (status == Status.STATUS_COMMITTED) {
notifyAllMyFriends();
}
}
});
} catch (RollbackException ignore) {
logger.fine("Not done due to setRollbackOnly");
} catch (Exception e) {
throw new RuntimeException(e);
}
}
Note: when I implement "notifyAllMyFriends" as an @Asynchronous call, the above provides all the features that I previously used JMS for, with all the unnecessary extra fat removed!