Asynchronous CDI events

CDI events can also be handled in an asynchronous way. The same holds true that the container will provide a thread for executing the event handling. To define asynchronous event handlers, the method is annotated with @ObservesAsync and the event is fired using the fireAsync() method. The next code snippets demonstrate asynchronous CDI events:

@Stateless
public class CarManufacturer {

    @Inject
    CarFactory carFactory;

    @Inject
    Event<CarCreated> carCreated;

    public Car manufactureCar(Specification spec) {
        Car car = carFactory.createCar(spec);
        carCreated.fireAsync(new CarCreated(spec));
        return car;
    }
}

The event handler is called in an own, container-managed thread:

import javax.enterprise.event.ObservesAsync;

public class CreatedCarListener {

    public void onCarCreated(@ObservesAsync CarCreated event) {
        // handle event asynchronously
    }
}

For backwards compatibility reasons, synchronous CDI events can also be handled in an EJB asynchronous method. Therefore, the events and handlers are defined in a synchronous way, but the handler method is an EJB business method annotated with @Asynchronous. Before asynchronous events were added to the CDI standard in Java EE 8, this was the only way to provide this feature. To avoid confusion, this implementation should be avoided in Java EE 8 and newer.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.218.31.165