Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does a Java Event, specifically the javax.enterprise.event.fire() behave?

Tags:

java

cdi

ejb

I have the following situation (running on JBoss AS6 and AS7):

  • An Singleton EJB with a scheduled method.
  • An injected Event of type SomethingChangedEvent

Consider the following examples:

@Singleton
public final class Scheduler {
    @Inject
    private Event<SomethingChangedEvent> event;

    @Schedule
    private void scheduleSomething() {
        event.fire(new SomethingChangedEvent());
    }
}

I would expect this event to be added to some kind of queue on the server and distributed by it. Any methods that observe this kind of event by using @Observers will be notified. The event.fire() method will return immediately.

However, I face the following problem: Sometimes, the event.fire() method takes like two or three minutes to return, causing havoc in my schedule since it is assumed to be invoked once every ten seconds.

So the questions are: How is this possible? What happens to events that are fired, but no one observes them? Is there a queue that can overflow?

Regards, Sven

like image 277
Sven Plath Avatar asked Jan 24 '13 10:01

Sven Plath


1 Answers

CDI event processing occurs synchronously. There is actually a proposal to include an asynchronous processing model into the spec, but it is still being voted on. In the meantime there are two ways 'forcing' asynchronous processing:

  1. Use JMS - yes this is a kludge because it is reverting back to older Java EE technologies. But it works
  2. Use an @Asynchronous method on both producer and observer methods, to split those method invocations into separate, container managed threads.

Applying second method to your code example:

@Singleton
public final class Scheduler {
    @Inject
    private Event<SomethingChangedEvent> event;

    @Asynchronous
    private void scheduleSomething() {
        event.fire(new SomethingChangedEvent());
    }
}
like image 171
Perception Avatar answered Sep 22 '22 10:09

Perception