Tuesday Apr 15, 2014

Asynchronous CDI Events?

CDI events are a very powerful feature that enable loose coupling in a very simple and type-safe way. One aspect of CDI events that surprises many folks is the fact that they are synchronous rather than asynchronous. The surprise is perhaps fairly natural as similar event systems are usually asynchronous. Piotr Nowicki explores the issue in a very well thought out post exploring the various options for making CDI events asynchronous using plain Java EE features such as EJB @Asynchronous, Singleton locks and JMS. Exploring this issue further is probably very timely with the gradual rise of node.js/Reactive Programming.

Very encouragingly CDI 2 specification lead Antoine Sabot-Durand himself mentioned asynchronous CDI events as a possibility in his personal CDI 2 wish list. He suggests adding an asynchronous flag to the @Observes annotation. A possible downside to this is that the consumer rather than the producer makes the decision to go asynchronous. Another possibility is putting the asynchronous marker on the producer possibly using the type annotations facility introduced in Java SE 8:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
public class EventProducer {
 
@Inject Event event;
 
public void doSomething() {
MyEvent e = new @Async MyEvent();
e.data = "This is a test event";
e.eventTime = new Date();
event.fire(e);
}
}
 
public class EventConsumer {
 
public void afterMyEvent(@Observes MyEvent event) {
// .. Insert event logic here
}
}
view raw CdiAsyncEvents.java hosted with ❤ by GitHub

What do you think about the issue and the possibilities? This is the time to sound off as the horizons for CDI 2 are emerging.