Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Asynchronous CDI Events?

DZone's Guide to

Asynchronous CDI Events?

· Java Zone
Free Resource

The single app analytics solutions to take your web and mobile apps to the next level.  Try today!  Brought to you in partnership with CA Technologies

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:

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
    }
}

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.

CA App Experience Analytics, a whole new level of visibility. Learn more. Brought to you in partnership with CA Technologies.

Topics:

Published at DZone with permission of Reza Rahman, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}