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

Bitbucket is for the code that takes us to Mars, decodes the human genome, or drives your next car. What will your code do? Get started with Bitbucket today, it's free.

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.

Bitbucket is the Git solution for professional teams who code with a purpose, not just as a hobby. Get started today, it's free.

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