Java EE 8: Sending asynchronous CDI 2.0 events with ManagedExecutorService

Java EE 8 with CDI 2.0 introduced asynchronous CDI Events. The Event interface was extended with the fireAsync method and an optional NotificationOptions parameter.

Now you can send events asynchronously, also using the injected ManagedExecutorService instance:


import java.time.LocalTime;
import java.util.concurrent.CompletionStage;
import javax.annotation.Resource;
import javax.ejb.Schedule;
import javax.ejb.Singleton;
import javax.ejb.Startup;
import javax.enterprise.concurrent.ManagedExecutorService;
import javax.enterprise.event.Event;
import javax.enterprise.event.NotificationOptions;
import javax.inject.Inject;

@Startup
@Singleton
public class EventSource {

    @Inject
    Event<String> fireAlarm;
    
    @Resource
    ManagedExecutorService threadPool;

    @Schedule(second = "*/5", minute = "*", hour = "*")
    public void send() {
        String event = "fire " + System.currentTimeMillis();
        CompletionStage<String> completion = this.fireAlarm.
        fireAsync(event, NotificationOptions.ofExecutor(threadPool)); // returns immediately
        completion.thenAccept(this::eventDelivered);
    }

    void eventDelivered(String event) {
        //...receipt after delivery
    }
}
Asynchronous events are received with the @ObservesAsync annotation:


import java.time.LocalTime;
import javax.enterprise.event.ObservesAsync;

public class EventSink {

    public void onFireNotification(@ObservesAsync String event) {
       //...
    }

}

See you at Java EE 8 on Java 9, at Munich Airport, Terminal 2


NEW: Online Workhop Effective WebApps without Frameworks is also coming to: MUC Airport.

Airport MUC workshops: Web (SPA, PWAs, Offline, Desktop, Mobile) Applications Essentials and Effective Web Applications. No migrations. #usetheplatform

Podcast: airhacks.fm and newsletter: airhacks.news

A book about rethinking Java EE Patterns

Comments:

Post a Comment:
  • HTML Syntax: NOT allowed
Online Workshops
realworldpatterns.com
...the last 150 posts
...the last 10 comments
License